Note that there are some explanatory texts on larger screens.

plurals
  1. POLoop through a multilevel JSON object having children of same name
    primarykey
    data
    text
    <p>I have a JSON object as follows.</p> <pre><code>{ "name":"Me", "groups": [ { "name":"My Garage", "groups":[ { "name":"My Cars", "groups":[], "tags":[ { "name":"Fiet Punto" }, { "name":"Gallardo" } ] }, { "name":"My Bikes", "groups":[] } ] }, { "name":"My Bank", "groups":[ { "name":"Swiss Bank", "groups":[] }, { "name":"Bank of America", "groups":[], "tags":[ { "name":"Account 1" }, { "name":"Account 2" } ] } ] } ], "tags":[ { "name":"My tag 1" }, { "name":"My tag 2" } ] } </code></pre> <p>My desired output is as follows:</p> <pre><code>Me --My Garage --My Cars --Fiet Punto --Gallardo --My Bikes --My Bank --Swiss Bank --Bank of America -- Account 1 -- Account 2 --My Tag 1 --My Tag 2 </code></pre> <p>I have a problem in building the recursion. What I want to do is:</p> <ul> <li>Take the root object.</li> <li>Print the <code>name</code>. </li> <li>Find if <code>groups</code> or <code>tags</code> exist in the object. </li> <li>if any of them exist then loop through the inner object.</li> <li>Apply the correct indentation and follow the steps above for the inner object.</li> </ul> <p>How can I achieve this?</p> <p>EDIT : </p> <pre><code>function getAllGroups(jsonObject) { //print the name of the current level object. $("body").append(jsonObject.name); //now if this object contains groups if( jsonObject.hasOwnProperty( 'groups' ) ) { //and if it is an array if( jsonObject.groups.length &gt; 0 ) { //then for each object in groups of this object, call the function again. $(jsonObject.groups).each(function(i, innerObject){ //print the index for debugging. console.log(i + innerObject.name); //make a recursive call to the function. getAllGroups(innerObject); }); } } else { console.log("does not exist anymore.") } } </code></pre> <p>I am unable to figure out how can I evaluate both <code>tags</code> and <code>groups</code> in parallel and print the names maintaining the level. </p> <p>More precisely I am not being able to figure out how to get the level of the tree.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload