gpt4 book ai didi

javascript - JS中根据一个属性值提取列表

转载 作者:行者123 更新时间:2023-11-30 20:44:57 25 4
gpt4 key购买 nike

我有这样的对象:

input = [  {value: 1,
week: 1,
year: 2017
},
{value: 10,
week: 30;
year: 2018
},
{value: 2,
week: 2,
year: 2018
},
{value:3,
week: 3,
year: 2017
}
]

我想获得这个对象:

{ 2017: {value : [1, 3],
week: [1, 3]
},
2018: {value : [10, 2],
week: [30, 2]
}
}

我从 _.groupBy(input, function(elem) {return elem.year}) 开始,但后来我卡住了。

最佳答案

你可以使用.reduce

let input = [{
value: 1,
week: 1,
year: 2017
},
{
value: 10,
week: 30,
year: 2018
},
{
value: 2,
week: 2,
year: 2018
},
{
value: 3,
week: 3,
year: 2017
}
];

let result = input.reduce((c, v) => {
c[v.year] = c[v.year] || {value: [], week: []};
c[v.year].value.push(v.value);
c[v.year].week.push(v.value);
return c;
}, {});

console.log(result);

文档:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

关于javascript - JS中根据一个属性值提取列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48809956/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com