我尝试将所有孩子的名字都归为父母。我在:
创建一棵树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方法中做到,但我不知道如何。但是为了更容易,我认为应该为此创建另一种方法。
我请求你的帮助。
答案 0 :(得分:1)
此提案访问所有节点并获取该节点的所有子节点。
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; }