根据某一字段的值进行分类重组源数据:var _arr = [{ aId: 1, bId: 11, cId: 112,
}, { aId: 1, bId: 11, cId: 113,
}, { aId: 1, bId: 12, cId: 114,
}, { aId: 2, bId: 21, cId: 211,
}]期望:[{
aId: 1,
children: [{
bId: 11,
children: [{
cId: 112
}, {
cId: 113
}]
}, {
bId: 12,
children: [{
cId: 114
}]
}]
}, {
aId: 2,
children: [{
bId: 21,
children: [{
cId: 211
}]
}]
}]
1 回答
缥缈止盈
TA贡献2041条经验 获得超4个赞
function rebuild (arr, key) { let res = [] let keycopy = JSON.parse(JSON.stringify(key)) let k = keycopy.shift() while (arr.length) { let obj = {} obj[k] = arr[0][k] let arrcopy = JSON.parse(JSON.stringify(arr)) obj.children = arrcopy.filter(val => val[k] === obj[k]).map(val => { delete val[k] return val }) res.push(obj) arr = arr.filter(val => val[k] !== obj[k]) } return res.map(val => keycopy.length ? { ...val, children: rebuild(val.children, keycopy) } : val) } rebuild(_arr,['aId','bId'])
添加回答
举报
0/150
提交
取消