Reputation: 3467
I want to create a diagram with d3.js using the tree layout. Instead of the common flare json structure with hierarchical children like:
{
"name":"bla",
"children":[
{
"name":"bla2",
"someattribute":"green"
}
]
}
I just have an array (of elements which represent a timestep). I always want the next element(s) of the array to be the child(ren) element of the current. So in fact I want a tree to be generated out of a flattened array. My idea was to change the children function of the tree layout like this:
var tree = d3.layout.tree()
.children(function(d,i) {
return data[(i+1)];
})
But only one element is displayed in the tree. I don't get it. Shouldn't it iterate over every element when calling tree.nodes
on data[0]
?
To clarify my request: I want to turn an array like [ele1, ele2, ele3]
into a tree graph that looks like:
ele1-->ele2-->ele3
Upvotes: 1
Views: 2735
Reputation: 22872
The real issue I see is that the function passed to .children()
needs to return an Array of children Objects, instead of a single Object as it is now, i.e.
var tree = d3.layout.tree()
.children(function(d,i) {
return i < data.length - 1; data.slice(i+1, i+2) : null;
})
It's also important that the leaf node (the last data Object in the array) returns null
instead of an empty list.
Using this approach, I created a working JSFiddle that will create a linear tree from an array of objects.
However, I agree with @LarsKotthoff's comment on your post; your code would be better served in terms maintainability and flexibility if you passed tree.nodes()
a root of an Object in hierarchical format.
Upvotes: 1