Saqib Ali
Saqib Ali

Reputation: 12625

How to initially make only selected nodes in this d3.js expanded?

I'm experimenting with and modifying this example of d3.js to draw a tree based on a JSON structure.

This tree starts out with the root node expanded, and all other nodes contracted.

But I want to modify it by passing in JSON array that is exemplified here:

expandedNodes = ["analytics", "flare", "graph", "scale"]

if expandedNodes is empty, I want the tree to start off in the position it already does (with only the root node expanded).

If expandedNodes is non-empty I want the tree to start out with only those nodes expanded that appear in expandededNodes (in this example as shown in the picture below)

enter image description here

How do I do it?

You can assume that

Upvotes: 0

Views: 201

Answers (1)

Cyril Cherian
Cyril Cherian

Reputation: 32327

You can do it like this:

  //array of expanded nodes
  expandedNodes = ["analytics", "flare", "graph", "scale"];
  function collapse(d) {
    if (d.children) {
      //if node present in expanded nodes array keep it open.
      if (expandedNodes.find(function(d1){ return d1 == d.name})){
        //expanded nodes children should be collapsed.
        d.children.forEach(collapse);
        return;
      }
      d.children.forEach(function(child){
        child.parent = d;
      });      
      d._children = d.children;
      d._children.forEach(collapse);
      d.children = null;
    }
  }

Working code here

Upvotes: 1

Related Questions