------------恢复内容开始------------
被分组数据类型:包含n多个对象的数据
代码示例:
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'))
调用这个getGroup方法得到的结果就是
{ aaa:[ {key: "aaa", name: "qqq", age: 30, money: 78}, {key: "aaa", name: "qqq", age: 13, money: 32} ], ddd:[ {key: "ddd", name: "ooo", age: 13, money: 50}, {key: "ddd", name: "888", age: 13, money: 88}, {key: "ddd", name: "gun", age: 19, money: 66} ], sss:[ {key: "sss", name: "iii", age: 13, money: 100}, {key: "sss", name: "mmm", age: 50, money: 90}, {key: "sss", name: "rtt", age: 15, money: 456} ], xxx:[ {key: "xxx", name: "yiyi", age: 12, money: 10} {key: "xxx", name: "heh", age: 13, money: 95} {key: "xxx", name: "opp", age: 15, money: 91} ] }
引用链接:https://www.cnblogs.com/wjs0509/p/14884691.html
------------恢复内容结束------------