【发布时间】:2023-04-06 22:34:01
【问题描述】:
我发现 _.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;
}, {}));
【问题讨论】:
-
由于您使用的是 lodash,请查看
_.groupBy。您可能需要额外的后处理步骤来实现最终的数据结构,但_.groupBy做了很多工作。
标签: javascript arrays node.js object