【发布时间】:2021-12-23 15:20:20
【问题描述】:
我有一个数组,我使用 .reduce 将数组的所有匹配 id 分组到具有 id 的新数组中。
问题是我的输出看起来像这样
[
{
CHb5591f5db2a546d3af: [ [Object], [Object] ],
CH5e86016c8b894d9d87: [ [Object], [Object], [Object], [Object], [Object], [Object] ]
}
]
我需要这样的输出
[
{id: CHb5591f5db2a546d3af, content: [ [Object], [Object] ]},
{id: CH5e86016c8b894d9d87, content: [ [Object], [Object], [Object], [Object], [Object], [Object] ]}
]
这是我对减速器功能的尝试
result = await response.reduce(function (a, i) {
a[i.messagesId] = a[i.messagesId] || []; //it generates a new property i.messagesId with an array if it does not exist (the value of not existing properties is undefined). if exist, it assign itself
a[i.messagesId].push(i);
return a;
}, Object.create({}));
【问题讨论】:
标签: javascript node.js reduce