371273
371273

Reputation: 5436

Recursively creating a JSON tree structure from arrays of objects

Here is my data structure:

{ projects: [
      { revisions: [
            { files: [] },
        ],
      }
  ],
  user: {}
}

Go to the jsFiddle here: http://jsfiddle.net/winduptoy/EXdDy/

I'm tyring to recursively create a JSON hierarchy structure of an object's parents and their ids. Check your console. Look at projects[0].revisions[0]._idTree, which contains the projects._id and revisions as a child of projects, just as expected. Now look at projects[0].revisions[0].files[0]._idTree, which contains projects.files as a sibling of projects.revisions, when files should be a child of projects.revisions. How do I fix this?

Upvotes: 1

Views: 8531

Answers (2)

NBaua
NBaua

Reputation: 684

I assume this is what you should be using:

http://www.jstree.com/

Upvotes: 1

Hui Zheng
Hui Zheng

Reputation: 10224

Please rewrite recurseTree like this:

function recurseTree(tree, newKey, newId) {
    if(angular.element.isEmptyObject(tree)) {
        tree[newKey] = {_id: newId};
        return;
    } 

    var child = null; // find current tree's child
    for(var key in tree) {
        if (key != '_id') {
            child = tree[key]; // found a child
            break;
        }
    }
    if (child) { // recursively process on child
        recurseTree(child, newKey, newId);
    } else { // no child, so just fill the tree
        tree[newKey] = {_id: newId};
    }
}

Upvotes: 1

Related Questions