后端返回的数据需要跟key值的不同来分组 代码:
let data = [
{ key: 'xxx', name: 'yiyi', age: 12, money: 10 },
{ key: 'sss', name: 'iii', age: 13, money: 100 },
{ key: 'ddd', name: 'ooo', age: 13, money: 50 },
{ key: 'sss', name: 'mmm', age: 50, money: 90 },
{ key: 'ddd', name: '888', age: 13, money: 88 },
{ key: 'aaa', name: 'qqq', age: 30, money: 78 },
{ key: 'aaa', name: 'qqq', age: 13, money: 32 },
{ key: 'xxx', name: 'heh', age: 13, money: 95 },
{ key: 'sss', name: 'rtt', age: 15, money: 456 },
{ key: 'xxx', name: 'opp', age: 15, money: 91 },
{ key: 'ddd', name: 'gun', age: 19, money: 66 },
];
//data是要被分组的数据[],key是分组依据的关键字
let getGroup=(data,key)=>{
let groups={};
data.forEach(c=>{
let value=c[key];
groups[value]=groups[value]||[];
groups[value].push(c);
});
return groups;
}
console.log(getGroup(data,'key'))