Reputation: 12625
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)
How do I do it?
You can assume that
findNode()
function written by Cyril here is available. expandedNodes
is valid such that if a node's name appears in it, so do all of it's ancestors names.Upvotes: 0
Views: 201
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