tree operation in D3 are done in the hierarchy module.
A tree will be passed to a hierarchical layout such as D3 - Treemap Layout
You must call the function node.sum or node.count before invoking a hierarchical layout that requires node.value, such as d3.treemap.
See also Nest
d3.hierarchy. See example
d3.hierarchy(data[, childrenFunction])
Default children accessor:
function children(d) {
return d.children;
}
from csv, see D3 - Stratify (From CSV to tree)
A tree have the following properties:
Null and the empty string are equivalent to undefined.
See d3/d3-hierarchy
data = {
"name": "0",
"children": [
{
"name": "1"
},
{
"name": "2",
"children": [
{
"name": "21"
},
{
"name": "22"
}
]
},
{
"name": "3"
},
{
"name": "4",
"children": [
{
"name": "41"
}
]
},
{
"name": "5"
}
]
}
tree = d3.hierarchy(data);
tree.count();
console.log("The leaf count is "+tree.value);
console.log("The leaves are: "+tree.leaves().map( d => d.data.name ));
tree.sum(function(d){ return d.name.length; });
console.log("The sum of all letters in the name is "+tree.value);
console.log("The descendants are: "+tree.descendants().map( d => d.data.name ));
var nodes = [];
tree.each( d => nodes.push(d.data.name) )
console.log("The Each function has visited the tree in this order: "+nodes);
var nodes = [];
tree.eachAfter( d => nodes.push(d.data.name) )
console.log("The eachAfter function has visited the tree in this order: "+nodes);
var nodes = [];
tree.eachBefore( d => nodes.push(d.data.name) )
console.log("The eachBefore function has visited the tree in this order: "+nodes);
console.log("The links are:");
console.log(tree.links().map( d => "Source:"+d.source.data.name+", Target: "+d.target.data.name));