飲歌長(zhǎng)嘯
2022-12-22 15:45:05
我需要通過(guò) id 將鏈接對(duì)象的數(shù)組重組為一個(gè)樹(shù)對(duì)象。深度級(jí)別未知,因此我認(rèn)為應(yīng)該遞歸完成。什么是最有效的方法?我有下一個(gè)對(duì)象數(shù)組:const arrObj = [ { "id": 1, "children": [ { "id": 2 }, { "id": 3 } ] }, { "id": 2, "children": [ { "id": 4 }, { "id": 5 } ] }, { "id": 3, "children": [ { "id": 6 } ] }, { "id": 4 }]我想重組只有一個(gè)對(duì)象,比如一棵樹(shù):const treeObj = { "id": 1, "children": [ { "id": 2, "children": [ { "id": 4 }, { "id": 5 } ] }, { "id": 3, "children": [ { "id": 6 } ] } ]}每個(gè)對(duì)象都有其他許多屬性。
1 回答

慕斯709654
TA貢獻(xiàn)1840條經(jīng)驗(yàn) 獲得超5個(gè)贊
您可以對(duì)所有children.
const arrObj = [ { "id": 1, "children": [ { "id": 2 }, { "id": 3 } ] }, { "id": 2, "children": [ { "id": 4 }, { "id": 5 } ] }, { "id": 3, "children": [ { "id": 6 } ] }, { "id": 4 } ];
const res = arrObj[0];//assuming the first element is the root
res.children = res.children.map(function getChildren(obj){
const child = arrObj.find(x => x.id === obj.id);
if(child?.children) child.children = child.children.map(getChildren);
return child || obj;
});
console.log(res);
添加回答
舉報(bào)
0/150
提交
取消