我发现 _.reduce 但它只保留一组信息。应该使用什么选项来组合类似的信息?
[
{
fruit: 'apple',
'color': 'red'
},
{
fruit: 'apple',
'color': 'green'
},
{
fruit: 'pear',
'color': 'yellow'
},
{
fruit: 'pear',
'color': 'green'
}
]
我想要的结果是:
var items = [
{
fruit: 'apple',
'color': 'red', 'green'
},
{
fruit: 'pear',
'color': 'green', 'yellow'
}
]
我当前使用 NodeJS 的代码是:
let result = Object.values(json.reduce((c, {fruit,...r}) => {
c[fruit] = c[fruit] || {fruit};
c[fruit] = Object.assign(c[fruit], r);
return c;
}, {}));
最佳答案
这是一种运行时间为 O(n) 而不是 O(n^2) 的方法:
const arr = [
{
fruit: 'apple',
'color': 'red',
},
{
fruit: 'apple',
'color': 'green',
},
{
fruit: 'pear',
'color': 'yellow',
},
{
fruit: 'pear',
'color': 'green',
},
];
const map = arr.reduce((acc, o) => {
if (acc[o.fruit]) {
acc[o.fruit].push(o.color);
} else {
acc[o.fruit] = [o.color];
}
return acc;
}, {});
const result = Object.keys(map).map(k => ({ fruit: k, colors: map[k] }));
console.log(result);
return result;
请注意,正如 Nick 的回答中所述,这种差异对于小数组不会产生影响,但如果数组很大,或者转换本身包含在循环中,则可能很重要。
关于Javascript 将项目组合到数组对象中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60481793/