Mam taka tablice:

  1. [{
  2. id:'x',
  3. parent:0,
  4. childrens:[
  5. {
  6. id:'y',
  7. parent:'x',
  8. childrens:[
  9. {
  10. id:'z',
  11. parent:'y'
  12. }
  13. ]
  14. }
  15. ]
  16. }]


Chciałbym to przejść rekurencyjnie i otrzymać takie coś:

  1.  
  2. [
  3. {
  4. id: 'x',
  5. childrenNames: ['y','z']
  6. }
  7. ]
  8.  


Taką tablicę jak w pierwszym przykładzie tworzę już rekurencyjnie w :

  1. GUI.prototype.buildTree = function(elements, parentId){
  2. var response = [];
  3. for(var elem in elements){
  4. if(elements[elem]['parent'] == parentId){
  5. var childrens = this.buildTree(elements, elements[elem]['id']);
  6. if(childrens.length > 0){
  7. elements[elem]['childrens'] = childrens;
  8. }
  9. response.push(elements[elem]);
  10. }
  11. }
  12. return response;
  13. };
  14.  
  15. var tree = this.buildTree(elements, 0);


pomoże ktoś? smile.gif

Moźna zamkąć poradziłem sobie w tej sposób:

  1. function getChildren(array) {
  2. var result = [];
  3. array.forEach(function iter(a) {
  4. var children = [];
  5. result.push({ id: a.id, children: children });
  6. this.push(a.id);
  7. if (Array.isArray(a.children)) {
  8. a.children.forEach(iter, children);
  9. Array.prototype.splice.apply(this, [this.length, 0].concat(children));
  10. }
  11. }, []);
  12. return result;
  13. }
  14.  
  15. var data = [{ id: 'x', parent: 0, children: [{ id: 'y', parent: "x", children: [{ id: 'z', parent: "y" }] }] }];
  16.  
  17. console.log(getChildren(data));