1

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
1
  • This looks like an abuse of the .children function to me -- even if it worked in this particular case, it would be prone to breaking in others. I would strongly recommend formatting your data in a way that makes children more explicit. Commented Nov 24, 2013 at 21:44

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.