1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
| let json1 = [ { id: 1 }, { id: 2, parentId: 1 }, { id: 3 }, { id: 4, parentId: 3 }, { id: 5, parentId: 4 } ]
function set(list) { let parents = list.filter(item => !item.parentId) let childs = list.filter(item => item.parentId) function setTreeList(parents, childs) { parents.forEach((par, i) => { childs.forEach((chil, j) => { if (par.id === chil.parentId) { par.childs = par.childs ? par.childs.push(chil) : [chil] let newChilds = JSON.parse(JSON.stringify(childs)) newChilds.splice(j, 1) setTreeList([chil], newChilds) } }) }); } setTreeList(parents, childs) return parents; }
console.log(JSON.stringify(set(json1), null, 2));
|