invincibleDudess
invincibleDudess

Reputation: 1782

D3.js: Expand tree till node n

I am right now creating an Org Chart using a D3.js Tree layout. The Organization chart will be opened by a logged in user and the requirement is to show the org chart opened to the user's node by default.

For example, if the logged in user is 'n', and the org chart is :

        j   m
       /   /
  b - e - k
 /
a - d - l - n
 \
  c- f - h
      \ 
       i

The user will see :

a - d - l - n

So, the problem statement is to expand the Org chart till a particular node where the node id/name is the logged in user.

Any help is welcome.

Upvotes: 3

Views: 2159

Answers (1)

Cyril Cherian
Cyril Cherian

Reputation: 32327

First set the parent object in each data object:

  function collapse(d) {
    if (d.children) {
      d._children = d.children;
      //set the parent object in all the children
      d._children.forEach(function(d1){d1.parent = d; collapse(d1);});
      d.children = null;
    }
  }

Write a find function which finds the node and opens all its parents.

function find(d, name) {
    if (d.name == name){
      while(d.parent){
        d = d.parent;
        click(d);//if found open its parent
      }
      return;
    }

    //recursively call find function on its children
    if (d.children) {
      d.children.forEach(function(d){find(d, name)});
    } else if(d._children){
      d._children.forEach(function(d){find(d, name)});
    }
  }

Now call the find function with the node you wish to see

  var name = "layout";//example open till you find the node layout
  find (root, name)

working code here

Upvotes: 6

Related Questions