Search code examples
javascriptarraysangularjstwitter-bootstrapself-reference

Convert from self-reference array into nested array in tree


I use angular-bootstrap-nav-tree

I have Array that i get from self-reference table Like this:

var obj = [
        {id:1,label:"Animal"},
        {id:2,label:"Vigitable"},
        {id:3,label:"Cats",parent:1},
        {id:4,label:"black cat",parent:3},
        {id:5,label:"orange",parent:2},
    ];

I want to convert it to be nested like this:

var convrted = [
        {id:1,label:"Animal",children[
         {id:3,label:"Cats",parent:1,children[{id:4,label:"black cat",parent:3}]}
        ]},
        {id:2,label:"Vigitable",children[
         {id:5,label:"orange",parent:2}
        ]}
];

I want it to work unlimited levels dynamic.


Solution

  • This will do the job:

    function nest (array) {
      nested = [];
      for (var i = 0; i < array.length; i++) {
        var parent = array[i].parent;
        if (!parent) {
          nested.push(array[i]);
        } else {
          // You'll want to replace this with a more efficient search
          for (var j = 0; j < array.length; j++) {
            if (array[j].id === parent) {
              array[j].children = array[j].children || [];
              array[j].children.push(array[i]);
            }
          }
        }
      }
      return nested;
    }
    

    The second for loop is an inefficient way of finding the parent; if you ever have more than a few items to nest, you'll want to replace it with something that doesn't scan the entire array.