我需要通过 id 将链接对象的数组重组为一个树对象。深度级别未知,因此我认为应该递归完成。什么是最有效的方法?我有下一个对象数组:const arrObj = [ { "id": 1, "children": [ { "id": 2 }, { "id": 3 } ] }, { "id": 2, "children": [ { "id": 4 }, { "id": 5 } ] }, { "id": 3, "children": [ { "id": 6 } ] }, { "id": 4 }]我想重组只有一个对象,比如一棵树:const treeObj = { "id": 1, "children": [ { "id": 2, "children": [ { "id": 4 }, { "id": 5 } ] }, { "id": 3, "children": [ { "id": 6 } ] } ]}每个对象都有其他许多属性。
1 回答

慕斯709654
TA贡献1840条经验 获得超5个赞
您可以对所有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);
添加回答
举报
0/150
提交
取消