d3 v4 tree layout dynamically add new nodes

1,349 views
Skip to first unread message

Shijo c j

unread,
Sep 7, 2017, 2:49:20 AM9/7/17
to d3-js
  
Hi all, I am working in D3.js Tree Layout Version 3 with https://jsfiddle.net/CJ_Shijo/e7osumLp/ 
example. 
I created above jsfiddle example using http://bl.ocks.org/benlyall/4fea200ebebb273aa4df to 
hide unrelated parent nodes while click on child node. I modified click event function of above 
example to add nodes dynamically while click on child nodes. Also added below two functions 
to add nodes dynamically to child nodes. 

function updateJson(node) {
var associatedItems = getNewData(node);
node._children = associatedItems;
// if the node has visible children, make them invisible
if (node.children) {
node._children = node.children;
node.all_children = node.children;
node.children = null;
}
// if the node has invisible children, make them visible
else {
node.children = node._children;
node.all_children = node._children;
node._children = null;
}
// update the view to reflect the new changes
if (node.children) {
node.children.forEach(function (n) {
n.hidden = false;
});
if (node.parent) {
node.parent.children = [node, ];
node.parent.hidden = true;
node.parent.children.filter(function (n) {
return n !== node;
}).forEach(function (n) {
n.hidden = true;
});
}
}

}

function getNewData(node) {
/* Return a list of things that will be added as children to the json. */
return [{
name: "E",
}, {
name: "F",
}, {
name: "G",
}
];
}

I have achieved this features using d3 V3 version. I need to achieve same features 
with d3 V4 version.


I have flat json data like below.

var flatData = [
  {"name": "Top Level", "parent": null}, 
  {"name": "Level 2: A", "parent": "Top Level" },
  {"name": "Level 2: B", "parent": "Top Level" },
  {"name": "Son Of A", "parent": "Level 2: A" },
  {"name": "Daughter Of A", "parent": "Level 2: A" }
];

By using below d3 methods I created hierarchical(tree) data.

var treeData = d3.stratify()
.id(function(d) { return d.name; })
.parentId(function(d) { return d.parent; })
(flatData);
treeData.each(function(d) { d.name = d.id;  }); 
var root = d3.hierarchy(treeData, function(d) { return d.children; });



This is the d3 V4 version example https://jsfiddle.net/CJ_Shijo/km4txwna/  I am working.
But I facing problem on adding nodes dynamically to leaf nodes. Can any one help me on 
the same in V4 version?

Reply all
Reply to author
Forward
0 new messages