我正在尝试动态根据属性的值将对象数组拆分成组。
以下是输入的示例:
`input = [
{"name": "john", "location": "first"},
{"name": "steve", "location": "first"},
{"name": "paul", "location": "another"},
{"name": "tony", "location": "random"},
{"name": "ant", "location": "random"}
]`
和所需的输出:
`solution(input, location) = [
first: [{"name": "john", "location": "first"},
{"name": "steve", "location": "first"}],
another: [{"name": "paul", "location": "another"}],
random: [{"name": "tony", "location": "random"},
{"name": "ant", "location": "random"}]
]`
我不知道位置可以是的值(但我知道密钥名称)
我试图避免使用任何外部库, (这是一个有角度的5项目) 但如果它变得非常容易,那么我就不会反对它。
提前致谢
答案 0 :(得分:2)
使用Array#reduce
:
const input = [{"name":"john","location":"first"},{"name":"steve","location":"first"},{"name":"paul","location":"another"},{"name":"tony","location":"random"},{"name":"ant","location":"random"}];
const group = input.reduce((acc, item) => {
if (!acc[item.location]) {
acc[item.location] = [];
}
acc[item.location].push(item);
return acc;
}, {})
console.log(group);

修改1
如果您想迭代结果,可以使用for...of
循环Object.entries
,如下所示:
for (let [location, persons] of Object.entries(group)) {
console.log(location, persons);
// do your stuff here
}