Mam taka tablice:
[{
id:'x',
parent:0,
childrens:[
{
id:'y',
parent:'x',
childrens:[
{
id:'z',
parent:'y'
}
]
}
]
}]
Chciałbym to przejść rekurencyjnie i otrzymać takie coś:
[
{
id: 'x',
childrenNames: ['y','z']
}
]
Taką tablicę jak w pierwszym przykładzie tworzę już rekurencyjnie w :
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;
};
var tree = this.buildTree(elements, 0);
pomoże ktoś?

Moźna zamkąć poradziłem sobie w tej sposób:
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));
Ten post edytował rad11 3.11.2016, 13:06:36