Pushing item into a multi-dimensional tree like structure in JavaScript


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 <a href="https://github.com/tautologistics/node-htmlparser" rel="nofollow">htmlparser</a>.

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?


First of all, looking at your structure of an object, it looks like structure of your root object is wrong. Root object cannot be an Array of the objects that you intend to have. To take advantage of recursion, you should have structure which is similar on all levels.

You function implementation is almost correct.

I just hope you are not passing JSON string as the json parameter; if you are, you have to parse it and make a JS object by using JSON.parse(json)

Here is updated implementation:

var obj = { id: 23, name: 'Test1', children: [{ id: 24, name: 'Test2', children: [] },{ id: 25, name: 'Test2', children: [] }], }; var objToBePushed = { id: 26, name: 'Test3', children: [{ id: 27, name: 'Test4', children: [] }] }; function findNode(nodeId, json, node){ if(node.id == nodeId){ node.children.push(json); } else{ for(var i=0; i<node.children.length; i++){ findNode(nodeId, json, node.children[i]); } } } findNode(24, objToBePushed, obj); console.log(obj);

Working JSFiddle: <a href="http://jsfiddle.net/ef3ewoag/2/" rel="nofollow">http://jsfiddle.net/ef3ewoag/2/</a>


you have to return the object

check this:

<a href="http://jsfiddle.net/rf7ysasy/" rel="nofollow">http://jsfiddle.net/rf7ysasy/</a>

var obj = [{ id: 23, name: 'Test1', children: [{ id: 24, name: 'Test2', children: [] },{ id: 25, name: 'Test2', children: [] }], }]; var findNode = function(nodeId, json, o){ if(o.id == nodeId){ o.children.push(json); } else{ if(o.children){ for(var i=0; i<o.children.length; i++){ o.children[i] = findNode(nodeId, json, o.children[i]); } } } return o; }; obj = findNode(24,{ id: 26, name: 'Test2', children: [] }, obj); console.log (obj);


  • How to select or find child node in a treeview
  • Password-protect the macros of a second workbook from a first using VBA
  • Count of Files in a Directory With Count of Files in Sub Directories Also Reported
  • Including data files with setup.py
  • Unknown C# type
  • What is the first step to using a REST API in Rails?
  • Recursion in ASP.NET Core Razor views
  • Insert space after period using sed
  • Cassandra 2.1: Recursion by nesting UDT's
  • @tailrec why does this method not compile with 'contains a recursive call not in tail position&
  • Changing references to deprecated methods C++
  • Python PIL to extract number from image
  • Configure nginx to return different files to different authenticated users with the same URI
  • Azure table store snapshot/backup capability
  • How to make JSON.NET deserialize to Microsoft Date Time?
  • How to get current document uri in XSLT?
  • Copy to all folders batch file?
  • Force show.bind execution
  • SharedPreferences or SQLite Database?
  • How to write order and limit within cakephp joins array
  • Play WS (2.2.1): post/put large request
  • D3 nodes and links from JSON with nested arrays of children
  • Disable Enter in editText android
  • Different response to non-authenticated users and AJAX calls
  • PHP - How to update data to MySQL when click a radio button
  • Join two tables and save into third-sql
  • How to handle AllServersUnavailable Exception
  • Akka Routing: Reply's send to router ends up as dead letters
  • Warning: Can't call setState (or forceUpdate) on an unmounted component
  • AT Commands to Send SMS not working in Windows 8.1
  • using conditional logic : check if record exists; if it does, update it, if not, create it
  • Rails 2: use form_for to build a form covering multiple objects of the same class
  • How do I configure my settings file to work with unit tests?
  • Linking SubReports Without LinkChild/LinkMaster
  • How can I remove ASP.NET Designer.cs files?
  • python draw pie shapes with colour filled
  • Is it possible to post an object from jquery to bottle.py?
  • Is there any way to bind data to data.frame by some index?
  • Easiest way to encapsulate a HTML5 webpage into an android app?
  • How can i traverse a binary tree from right to left in java?