假设有如下嵌套数组的数据:
let data = [
{ id: 1, name: 'John', group: 'A', score: 80 },
{ id: 2, name: 'Mike', group: 'B', score: 90 },
{ id: 3, name: 'Sarah', group: 'A', score: 75 },
{ id: 4, name: 'Emily', group: 'B', score: 85 },
{ id: 5, name: 'Tom', group: 'C', score: 95 },
{ id: 6, name: 'Jane', group: 'C', score: 70 },
];
我们可以通过以下方法按特定键group
进行分组:
const groupBy = (arr, key) => {
return arr.reduce((acc, curr) => {
(acc[curr[key]] = acc[curr[key]] || []).push(curr);
return acc;
}, {});
}
let groupedData = groupBy(data, 'group');
console.log(groupedData);
输出结果为:
{
'A': [
{ id: 1, name: 'John', group: 'A', score: 80 },
{ id: 3, name: 'Sarah', group: 'A', score: 75 }
],
'B': [
{ id: 2, name: 'Mike', group: 'B', score: 90 },
{ id: 4, name: 'Emily', group: 'B', score: 85 }
],
'C': [
{ id: 5, name: 'Tom', group: 'C', score: 95 },
{ id: 6, name: 'Jane', group: 'C', score: 70 }
]
}
可以看到,我们成功地将数据按照group
键进行了分组,并返回了一个新的对象,其中每个键都对应一个数组,数组中包含了原始数据中符合该键的所有对象。