![](/img/trans.png)
[英]How to create a tree (parent-child) object from Array in Javascript
[英]Create a tree structure from an array with parent-child references
我正在嘗試將片段中的 json 更改為樹結構,就像在https://www.primefaces.org/primeng/#/treetable中一樣(下面是示例)。 我知道它涉及遞歸,但我不確定如何深入鏈接每個。
我期望的 output 如下所示。 其父為 true 的 json 成為根。 如果根有值,則與該值的 id 對應的 json 被推送到子數組,其中 json object “數據”。 同樣,如果 json 有值,則對應於值的 id 的 json 將被推送到子數組,其中包含 json ZA8CFDE633111BD59EB2AC96Fdata 和 so on
我寫的代碼只是一個初始階段。 需要有關如何通過迭代完成嵌套的幫助。
[
{
"data": {
"parent": true,
"id": "C001",
"type": "Folder",
"values": [
{
"id": "P001",
"type": "File"
}
]
},
"children": [
{
"data": {
"parent": false,
"id": "P001",
"type": "File",
"values": [
{
"id": "P002",
"type": "Image"
}
]
},
"children": [
{
"data": {
"parent": false,
"id": "P002",
"type": "Image",
"values": [
]
}
}
]
}
]
},
{
"data": {
"parent": true,
"id": "S000",
"type": "Something",
"values": [
]
}
}
]
var junkdata=[ { "parent": false, "id": "P001", "type":"File", "values": [ { "id": "P002", "type": "Image" } ] }, { "parent": true, "id": "C001", "type": "Folder", "values": [ { "id": "P001", "type": "File" }] }, { "parent": false, "id": "P002", "type": "Image", "values":[] }, { "parent": true, "id": "S000", "type": "Something", "values":[] }]; var parentDatas=junkdata.filter((x)=>x.parent==true); if(parentDatas.length>0){ var finalResponse=parentDatas.map((parentData)=>{ var resultJson={}; resultJson.data=parentData; if(parentData.values.length>0){ resultJson.children=[]; for(var i of parentData.values){ var child=junkdata.find((x)=>x.id==i.id); if(child){ var jsonObj={}; jsonObj.data=child; resultJson.children.push(jsonObj); } } } return resultJson; }) } console.log(JSON.stringify(finalResponse));
基本上,我們可以從這個開始處理根節點:
let tree = yourData.filter(x => x.parent).map(process);
其中process
是處理給定節點的遞歸 function:
let process = node => ({
id: node.id,
type: node.type,
children: node.values.map(x => process(
yourData.find(y => y.id === x.id)))
});
對於node.values
中的每個id
,它會找到具有該id
的節點並遞歸調用它的process
。 處理完所有子節點后, process
將它們收集到一個數組中並返回新格式化的 object。
這是使用類似圖形的結構的一般遞歸模式,其中“節點”以某種方式連接到其他“節點”:
function F (N: node) {
for each node M which is connected to N {
F (M) <--- recursion
}
result = do something with N
return result
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.