Skip to content

Instantly share code, notes, and snippets.

@LevelbossMike
Created May 6, 2012 17:22
Show Gist options
  • Save LevelbossMike/2623382 to your computer and use it in GitHub Desktop.
Save LevelbossMike/2623382 to your computer and use it in GitHub Desktop.
creating table from array of json with d3
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://mbostock.github.com/d3/d3.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
</head>
<body>
<table id="split">
<thead></thead>
<tbody></tbody>
</table>
<script type="text/javascript">
var sessions = new Array(
{id: 1, distance: 50},
{id: 2, distance: 50},
{id: 3, distance: 50},
{id: 4, distance: 50},
{id: 6, distance: 70}
);
// create the table header
var thead = d3.select("thead").selectAll("th")
.data(d3.keys(sessions[0]))
.enter().append("th").text(function(d){return d});
// fill the table
// create rows
var tr = d3.select("tbody").selectAll("tr")
.data(sessions).enter().append("tr")
// cells
var td = tr.selectAll("td")
.data(function(d){return d3.values(d)})
.enter().append("td")
.text(function(d) {return d})
</script>
</body>
</html>
@robert-moore
Copy link

Great, thank you!

@theredpea
Copy link

Hi @LevelbossMike, this is great, but I have two questions:

  1. I think your code creates thead > th -- but I think the "technically correct" thead looks like thead > tr > th . This could cause confusion if someone uses the selector 'tr' and expects to only get the non-header rows, but you prevent this by using the nested selection d3.select('tbody').selectAll('tr') -- which excludes header rows.
  2. You enter() your headers (th) using d3.keys() and your cells (td) using d3.values() -- but both of those say "order of the returned array is undefined", which means the headers could appear in a different order than the values. Right?

@massimobortolato
Copy link

How do you manage table updates?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment