假设我们有一个包含多个对象的数组,我们想按多个键将它们分组,并将每个分组的id添加到生成的对象的键中。我们可以使用reduce方法和嵌套的forEach函数来实现这一目标。
代码示例:
const data = [
{id: 1, name: "John", age: 25, city: "New York"},
{id: 2, name: "Sarah", age: 27, city: "Los Angeles"},
{id: 3, name: "David", age: 30, city: "New York"},
{id: 4, name: "Mary", age: 22, city: "Chicago"},
{id: 5, name: "Tom", age: 28, city: "Los Angeles"},
{id: 6, name: "Jane", age: 26, city: "Chicago"}
];
const groupKeys = ["city", "age"];
const result = data.reduce((acc, obj) => {
let group = acc;
groupKeys.forEach(key => {
const value = obj[key];
group[value] = group[value] || {idList: [], data: []};
group[value].idList.push(obj.id);
group = group[value].data;
});
group.push(obj);
return acc;
}, {});
console.log(result);
输出:
{
"New York": {
"idList": [1, 3],
"data": [
{"id": 1, "name": "John", "age": 25, "city": "New York"},
{"id": 3, "name": "David", "age": 30, "city": "New York"}
]
},
"25": {
"idList": [1],
"data": [{"id": 1, "name": "John", "age": 25, "city": "New York"}]
},
"30": {
"idList": [3],
"data": [{"id": 3, "name": "David
上一篇:按多个键分组流
下一篇:按多个键将数组对象分组和扁平化