[英]return a new object with keys from array
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:我正在尝试从下面的
people
数组中创建一个新对象,使用born
作为键,其中包含该年出生的所有人员:
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/ jsfiddle 设置在这里: https ://jsfiddle.net/jw9n3bmr/
Here is a solution with reduce
for what you want to do:以下是针对您想要执行的操作使用
reduce
的解决方案:
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);
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"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.