Reputation: 10947
I am trying to create a new object from the people
array below, using born
as a key, that contains all the people born in that year:
const newObject = {
'1971': {
male: [ [Object], [Object] ],
female: [ [Object] ]
},
'1972': {
male: [ [Object], [Object] ],
female: [ [Object] ]
}
}
Here is my code so far:
people.map(person => {
let {
born,
sex
} = person;
newPeople[born] = sex == "male" ? {
male: Array.isArray(male) && array.length ? male.push(person) : [],
female: Array.isArray(female) && female.length ? female.push(person) : []}
})
Array of people:
const people = [{
name: 'Jim',
sex: 'male',
born: '1971',
address: {
town: 'London',
},
},
{
name: 'Bob',
sex: 'male',
born: '1971',
address: {
town: 'London',
},
},....
jsfiddle setup here: https://jsfiddle.net/jw9n3bmr/
Upvotes: 0
Views: 59
Reputation: 690
I hope this could helps.
const getItems = (array, key, value) => {
let items = [];
array.forEach((k, o) => { if (o[key] === value) items.push(o) });
return items;
};
console.log(getItems(people, "born", "1971"));
Upvotes: 0
Reputation: 31805
Here is a solution with reduce
for what you want to do:
const people = [{
name: 'Jim',
sex: 'male',
born: '1971',
address: {
town: 'London',
},
},
{
name: 'Bob',
sex: 'male',
born: '1971',
address: {
town: 'London',
},
}
];
const result = people.reduce((acc, currVal) => {
(acc[currVal.born] || (acc[currVal.born] = { male: [], female: [] }))[currVal.sex].push(currVal);
return acc;
}, {});
console.log(result);
Upvotes: 1