1

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 ??

6
  • 2
    Do you control the data sent from back end? Sending flat array isn't nearly as clean as sending nested arrays with same property keys at each level. Please also show attempts to solve this Commented Jul 24, 2015 at 3:21
  • Yes, trying to control data coming from backend. Tried using for.Each function but it didn't render as per the parent child relationship. Commented Jul 24, 2015 at 3:39
  • @Sree you can do parent child relationship to array in JavaScript too. If not getting solution from backend. It should be like { node_ID = '1', name = 'Node1', role = 'rootNode', child = [{ node_ID = '3', name = 'Child2', role = 'Node', child = [{ node_ID = '2', name = 'Child3', role = 'leafNode', child = [] }, { node_ID = '4', name = 'Child4', role = 'leafNode', child = [] }] }] }, Commented Jul 24, 2015 at 3:45
  • show us what you tried even if it's not working. That's the whole idea of this site....you show the code that is giving problems, people try to help you fix it. Without seeing some effort it then appears you are asking others to do all of your work for you. It might be something simple you need...in which case it means we don't have to build it from nothing Commented Jul 24, 2015 at 3:53
  • Also suggest you google angular recursive directive Commented Jul 24, 2015 at 3:56

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.