let arr = [{a:21,b:22,c:5},{a:11,b:21,c:4},{a:31,b:'2a',c:4},{a:'1aaa',b:'2a',c:5}]
我想合并成
let arr2 = [{c:4,child:[{a:11,b:21,c:4},{a:31,b:'2a',c:4}]},{c:5,child:[{a:21,b:22,c:5},{a:'1aaa',b:'2a',c:5}]}];
就是把 C 4 相同的数据,整合到一个数组下面
1
shintendo 2019-12-10 10:05:12 +08:00
lodash.groupBy
|
2
shintendo 2019-12-10 10:11:19 +08:00
原生的话:[...Set(arr.map(x => x.c))].map(c => ({c, child: arr.filter(x => x.c === c)}))
|
3
shintendo 2019-12-10 10:12:21 +08:00
少了个 new
[...new Set(arr.map(x => x.c))].map(c => ({c, child: arr.filter(x => x.c === c)})) |
4
otakustay 2019-12-10 11:12:48 +08:00
const groups = groupBy(arr, i => i.c);
Object.entries(groups).map(([c, child]) => ({c, child})); |
6
Colorful OP 第一次了解 groupBy 这个语法,太感谢了
|