[英]How get recursively parent children names
I try to get all children names to parent all of them. 我试图将所有孩子的名字都归为父母。 I`m create a tree in:
我在这里创建了一棵树:
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;
};
My input from buildTree method looks like: 我从buildTree方法输入的内容如下:
[{
"id" : 'x',
"parent" : 0,
"childrens" : [{
"id" : 'y',
"parent" : "x",
"childrens" : [{
"id" : 'z',
"parent" : "y"
}]
}]
}]
and I would like to output like: 我想输出如下:
[{
"id": "x",
"childrenNames": ["y", "z"]
}]
The best opion could be do it in buildTree method but I dont know how. 最好的opion可以在buildTree方法中做到,但我不知道如何。 But for more easly i think should be create another method for that.
但是为了更容易,我认为应该为此创建另一种方法。
I ask for your help. 我请求你的帮助。
This proposal visits all nodes and gets all children for the node. 此提案访问所有节点并获取节点的所有子节点。
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.