Sree
Sree

Reputation: 21

Iterating through JSON using angular.forEach

I am having a JSON string that contains all my parent and child nodes. I need to render the parent node and its corresponding child nodes as a list in the navigation bar.

Here is my json:

    [
      {node_ID='2', name='Child3', parent='3', role ='leafNode'},
      {node_ID='4', name='Child4', parent='3', role ='leafNode'},
      {node_ID='3', name='Child2', parent='1', role ='Node'},
      {node_ID='1', name='Node1', parent='0', role ='rootNode'},

... ]

After Iterating my list should be displayed as:

          > Node1
            >Child2
              >Child3
              >Child4

Can someone provide solution for it using angular.forEach function to traverse along the JSIN array and sort the nodes based on their node-ID and Parent-ID ??

Upvotes: 1

Views: 230

Answers (1)

charlietfl
charlietfl

Reputation: 171679

This will map your data into a nested array suitable for passing to a recursive tree directive. It shouldn't be hard to find one of those in a web search...there are lots and lots of examples and modules

var tmp ={}, res=[];

data.forEach(function(item){
   item.children =[];
   tmp[item.node_ID]=item;
});

data.forEach(function(item){
  if(+item.parent !==0){
    tmp[item.parent].children.push(item);
  }else{
    res.push(item);
  }
});

delete tmp;


$scope.tree = res;

DEMO

Upvotes: 2

Related Questions