2

I have some JavaScript code I have inherited. It draws a hierarchical tree based on json data (using D3 version 3 library). The code works. I need to make a minor modification, but HOW to make the modification is the problem. I have an object called treeData. treeData is a hierarchical listing of nodes in the tree. Each node has properties, such as name, id, depth, x, y, and children. Children is an array, which points to child nodes of the current node. So children can have children, can have children, etc. If I look at the treeData object, I see the 'root' node, and I see that it has 10 children.

enter image description here

The children array is structurally the same as the parent... This shows expanding the first child, and I see that it has 3 children. My data is typically 3-4 levels deep. enter image description here

My challenge is that I need to run a function against all nodes in the tree. I am sure that there is an elegant way of doing this, but I don't know what it would be... I need something like..

var myNode;
for (var zz = 0; zz <= treeData.children.length; zz++) {
myNode = treeData.children[zz];
collapseNode(myNode);
}

The problem is that this just looks at one level, not traversing the hierarchy... How do I rewrite this to visit each node in the hierarchy?

user1009073
  • 3,160
  • 7
  • 40
  • 82

3 Answers3

1

Try this -

function traverse(o) {
    for (i in o) {
        // if o is an object, traverse it again
        if (!!o[i] && typeof(o[i])=="object") {
            console.log(i, o[i])
            traverse(o[i]);
        }
    }
}
Tushar Walzade
  • 3,737
  • 4
  • 33
  • 56
0
function traverse(array){
  for(const obj of array){
     //do whatever with obj, than go deeper
     traverse(obj.children);
  }
}

Thats quite simple if you go deep by recursion.

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
0

Try this recursive approach

function processNode(node)
{
    collapseNode(myNode); //logic for current node
    (treeData.children || []).forEach( function( chidNode ){
       processNode( chidNode ); //if there are children invoke the same method for each child node
    });
}
processNode( treeData ); //invoke for your treeData
gurvinder372
  • 66,980
  • 10
  • 72
  • 94
  • I cannot get the line ... (treeData.children || []).forEach( function( chidNode ){ ... to traverse. It appears to only call the current node and one of the child nodes.... – user1009073 Nov 29 '17 at 15:01
  • @user1009073 Can you please share some sample data for `treeData` for me to test this? – gurvinder372 Nov 30 '17 at 05:28