Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You can do the job in one pass using object as an associative array:</p> <pre><code>var test_items = [ { title:'child element 2.2', type:'e', id:6, parent:4 }, { title:'child element 2.1', type:'e', id:5, parent:4 }, { title:'container 1', type:'c', id:1, parent:0 }, { title:'container 2', type:'c', id:4, parent:0 }, { title:'child element 1.1', type:'e', id:2, parent:1 }, { title:'child element 1.2', type:'e', id:3, parent:1 }, { title:'element without parent A', type:'e', id:8, parent:0 }, { title:'element without parent B', type:'e', id:7, parent:0 } ]; function itemsToTree2( items ) { var tree2 = {}; for( var i=0; i&lt;items.length; ++i ) { var item = items[i]; if( item.type=='c' || item.parent==0 ) { if( !tree2[item.id] ) { var parent = { id:item.id, parent:0, children:[] }; tree2[item.id] = parent; } tree2[item.id].title = item.title; tree2[item.id].type = 'c'; } else { if( !tree2[item.parent] ) { var parent = { id:item.parent, parent:0, children:[] }; tree2[item.parent] = parent; } tree2[item.parent].children.push(item); } } return tree2; } var test_tree2 = itemsToTree2(test_items); console.log(test_tree2); </code></pre> <p>Not sure if it will be significantly faster... And if you know that every container will appear before its elements in the input data - the code above can be simplified:</p> <pre><code>function itemsToTree2( items ) { var tree2 = {}; for( var i=0; i&lt;items.length; ++i ) { var item = items[i]; if( item.type=='c' || item.parent==0 ) { item.children = []; tree2[item.id] = item; } else { tree2[item.parent].children.push(item); } } return tree2; } </code></pre> <p>If you need to alphabetically sort the tree (by title) levelwise (which is very often the case) you will need extra processing:</p> <pre><code>function sortTree2( tree2, comparator ) { var tree2array = []; for( var id in tree2 ) tree2array.push( tree2[id] ); tree2array.sort(comparator); for( var i=0; i&lt;tree2array.length; ++i ) tree2array[i].children.sort(comparator); return tree2array; } var sorted_tree2 = sortTree2( test_tree2, function(a,b) { return a.title &gt; b.title; }); console.log(sorted_tree2); </code></pre> <p>General solution for trees deeper than 2 levels exists too. It uses resembling approach and is not much more complex than this.</p>
    singulars
    1. This table or related slice is empty.
    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.
    1. This table or related slice is empty.
    1. VO
      singulars
      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