- 此问题在此处已有答案**:
Javascript - group array of objects by common values with label(5个答案)
昨天关门了。
我有以下reduce函数,它按类别对用户指南对象数组进行分组:
const groupByCategory = newUserGuides.reduce((group, userGuide) => {
const { category } = userGuide;
group[category] = group[category] ?? [];
group[category].push(userGuide);
return group;
}, {});
下面是我的原始数组:
[
{
category: "Data",
description: "user guide 1",
name: "User Guide 1"
},
{
category: "Data",
description: "user guide 2",
name: "User Guide 2"
},
{
category: "Pupils",
description: "user guide 3",
name: "User Guide 3"
}
]
但是,它将以如下方式返回:
{
Data: (3) [{…}, {…}, {…}],
Pupils: (3) [{…}, {…}, {…}]
}
有没有办法像对象数组一样返回它:
[
{category: 'Data', user_guides: [{...}]},
{category: 'Pupils', user_guides: [{...}]}
]
2条答案
按热度按时间to94eoyn1#
数组可以直接由
.reduce()
生成,但回调变得复杂,因为它需要标识要更新的数组的正确项。让它保持原样,然后处理
groupByCategory
的条目以获得预期结果:查看实际应用:
了解
Object.entries()
。bis0qfac2#