martinb
martinb

Reputation: 175

Populate table with D3

I'm trying to populate a table with data using D3 but trying to understand how to get this to work. I'm using D3 version 5. Thank you.

 <table>
    <tr>
        <th></th><th></th><th></th>
    </tr>
    <tr>
        <td></td><td></td><td></td>
    </tr>
</table>

For starters I want to populate the th with the object key and populate the td keys value.

// D3 code

categories_all = [{"CAT 1":11}, {"CAT 2":12}, {"CAT 3":13}];

const table = d3.select('table');
table.selectAll('th').data(categories_all).enter().text(function(d){
    return d;
});

I can iterate using the following pattern with plain javascript but how would this translate to D3?

for (let i = 0; i < categories_all.length; i++) {
    for (let key in categories_all[i]) {
        console.log(key);
    }
}

Upvotes: 0

Views: 554

Answers (1)

maag
maag

Reputation: 134

As Coderino Javarino has mentioned, if you're using D3 at all then I'd recommend using it to create the table too.

However, assuming table DOM elements do already exist, then the following should populate the table:

categories_all = [{"CAT 1":11}, {"CAT 2":12}, {"CAT 3":13}];

const table = d3.select('table');
table.selectAll('th').data(categories_all).text(function(d){
    return Object.keys(d)[0];
});  

table.selectAll('td').data(categories_all).text(function(d){
    return Object.values(d)[0];
}); 

enter() is only required if you're creating new elements.

Even though the above will do the trick, you're probably better off restructuring the data to something like:

categories_all = [{key: "CAT 1", value: 11}, {key: "CAT 2", value: 12}, {key: "CAT 3", value: 13}];

That way you can access the keys and values as d.key and d.value respectively.

Upvotes: 1

Related Questions