moarCoffee
moarCoffee

Reputation: 1309

Making a nested/hierarchical set of tables using D3

I have some data which I want to display in html tables using d3. My data is laid out like this:

var dataset = [
    {
        'name': 'foo',
        'children': [
            {
                'var1': 'hello',
                'var2': 87,
                ...
            },
            {...},
            {...}
        ]
    },
    {
        'name': 'bar',
        'children': [
            {
                'var1': 'howdy',
                ...
            },
            {...},
        ]
    },
    {
        // and so on...
    }
]

Ultimately, I would like to have something similar in style/functionality to this example, where the user can click on the 'foo' row and see everything in the 'foo' group. But for now I'm struggling to display the data at all.

I've made a little jsfiddle to show where I am now. As you can see, I have so far been unsuccessful at showing any of the actual numbers from my data. Does anyone have any ideas on how I should go about this? Should I restructure dataset? Thank you

== EDIT ==

I must apologise for maybe being vague about what I'm trying to do. Here is a mock up of what I ultimately want to achieve, although I stress that this question is more about binding data than layout/transition stuff.

Upvotes: 1

Views: 1303

Answers (1)

Ray Waldin
Ray Waldin

Reputation: 3227

Here's what I would do: http://jsfiddle.net/j43Nb/

Looking at your data, it seems more appropriate to have one table per parent and one row per child, and not wrap the whole thing in one big table. If you really need one big table, just replace the div.section/h4 bits with another table/tr/td sequence.

The key to understanding how "child" objects become an array of cell data is in this bit at the end:

var cells = rows.selectAll('td')
    .data(function(d) {
        // return cell data as an array of prop values, 
        // ordered according to prop names in cols
        return cols.map(function(prop) {
            return d[prop];
        })
    });

where the field names in cols are used to build a corresponding array of cell values for each given row (child).

Upvotes: 2

Related Questions