I have an array of objects which goes on something like this
var obj = [{
id: 23,
name: 'Test1',
children: [{
id: 24,
name: 'Test2,
children: [..]
},{
id: 25,
name: 'Test2,
children: [..]
}],
},{..}]
Each children can have multiple sub children, so basically I am trying to represent a graph like structure, similar to the output of htmlparser.
I need a function like this:
function(nodeId, json){}
The function will need to find the json object in the tree by using the nodeId and insert the json as a children of that parent object. Thats where I am stuck.
I tried writing a recursive function like this to search the appropriate node, however, the trouble arises when I have to insert the json into the actual obj array.
function findNode(nodeId, json, obj){
if(obj.id == nodeId){
obj.children.push(json);
}
else{
for(var i=0; i<obj.children.length; i++){
findNode(nodeId, json, obj.children[i]);
}
}
}
It seems the json gets inserted to the obj local to the recursive function, not the actual root obj. How can I can insert it to the parent obj?