1

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?

asked Dec 30, 2012 at 3:58
5
  • you never change newKey, and newId parameters that you pass to the recurseTree function. Commented Dec 30, 2012 at 4:04
  • Are you sure? I think I do. Look two lines down, I recursively call attachIDs(data[key][item], ...) in itself, so in the second recursive call, data is actually data[key][item]. Commented Dec 30, 2012 at 4:09
  • I mean inside the body of recurseTree it calls itself recursively with the same second and third parameters. Commented Dec 30, 2012 at 4:10
  • That's correct. If tree[key] is an object, I want to keep going to the deepest level of that object before I apply newKey and newId, it seems like that shouldn't matter, since those are just the new properties I will be applying. Commented Dec 30, 2012 at 4:18
  • Looks like the problem was with how I was dealing with my recurseTree() function. Hui Zheng posted a better version here: stackoverflow.com/questions/14087914/… Commented Dec 30, 2012 at 4:27

2 Answers 2

1

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};
 }
}
answered Dec 30, 2012 at 4:37
Sign up to request clarification or add additional context in comments.

Comments

1

I assume this is what you should be using:

http://www.jstree.com/

halfer
20.2k20 gold badges111 silver badges208 bronze badges
answered Dec 30, 2012 at 4:35

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.