[英]Best way to reorganize array of objects
我需要通過 id 將鏈接對象的數組重組為只有一棵樹 object。 深度級別是未知的,所以我認為應該遞歸地完成。 最有效的方法是什么?
我有下一個對象數組:
const arrObj = [
{
"id": 1,
"children": [
{
"id": 2
},
{
"id": 3
}
]
},
{
"id": 2,
"children": [
{
"id": 4
},
{
"id": 5
}
]
},
{
"id": 3,
"children": [
{
"id": 6
}
]
},
{
"id": 4
}
]
我想重組為只有一個 object 像一棵樹:
const treeObj = {
"id": 1,
"children": [
{
"id": 2,
"children": [
{
"id": 4
},
{
"id": 5
}
]
},
{
"id": 3,
"children": [
{
"id": 6
}
]
}
]
}
每個 object 都有其他許多屬性。
您可以對所有children
使用遞歸映射 function 。
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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.