[英]How get recursively parent children names
我試圖將所有孩子的名字都歸為父母。 我在這里創建了一棵樹:
GUI.prototype.buildTree = function(elements, parentId){
var response = [];
for(var elem in elements){
if(elements[elem]['parent'] == parentId){
var childrens = this.buildTree(elements, elements[elem]['id']);
if(childrens.length > 0){
elements[elem]['childrens'] = childrens;
}
response.push(elements[elem]);
}
}
return response;
};
我從buildTree方法輸入的內容如下:
[{
"id" : 'x',
"parent" : 0,
"childrens" : [{
"id" : 'y',
"parent" : "x",
"childrens" : [{
"id" : 'z',
"parent" : "y"
}]
}]
}]
我想輸出如下:
[{
"id": "x",
"childrenNames": ["y", "z"]
}]
最好的opion可以在buildTree方法中做到,但我不知道如何。 但是為了更容易,我認為應該為此創建另一種方法。
我請求你的幫助。
此提案訪問所有節點並獲取節點的所有子節點。
function getChildren(array) { var result = []; array.forEach(function iter(a) { var children = []; result.push({ id: a.id, children: children }); this.push(a.id); if (Array.isArray(a.children)) { a.children.forEach(iter, children); Array.prototype.splice.apply(this, [this.length, 0].concat(children)); } }, []); return result; } var data = [{ id: 'x', parent: 0, children: [{ id: 'y', parent: "x", children: [{ id: 'z', parent: "y" }] }] }]; console.log(getChildren(data));
.as-console-wrapper { max-height: 100% !important; top: 0; }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.