I have a JSON tree structure:
nodes =
[
{
"name": "user1",
"children": [
{
"name": "user2"
},
{
"name": "user3",
"children": [
{
"name": "user4"
}
]
},
{
"name": "user5"
}
]
}
]
that I would like to convert to a parent-link structure:
[{"name": "user1","parent": "null"},
{"name": "user2","parent": "user1"},
{"name": "user3","parent": "user1"},
{"name": "user4","parent": "user3"},
{"name": "user5","parent": "user1"}]
I have tried to traverse the tree recursively but without success accessing the parent object:
rebuild(nodes,parentLink);
function parentlink(key,value) {
var obj = { name: value , parent: ??? };
if (key == "name"){
nodes.push(obj);
}
}
function rebuild(o,func) {
for (i in o) {
func.apply(this,[i,o[i]])
if (typeof(o[i])=="object") {
traverse(o[i],func,nodes);
}
}
}
In developer tools I can see the parent objects for each child, but I don’t know how to access them. What should I do to add the parent to each user?
I’m not gonna lie, I didn’t bother looking at your code – this is how I would do it:
http://jsfiddle.net/J6G2W/1/
Output is:
Which seems to be what you’re looking for. You’re welcome to modify what of my code to work more like yours, I just thought I’d share what I’d do 🙂
UPDATE:
If, for some reason, you want to make it more extendable, you can customize which keys are the “name” and which are the “children”…for example:
http://jsfiddle.net/J6G2W/2/
Notice how you only have to specify the
key_look, children_lookarguments once. The inner function can access those parameters while only passing the important things each recursion. This probably isn’t important, I just wanted to figure it out 🙂