Created
May 6, 2012 17:22
-
-
Save LevelbossMike/2623382 to your computer and use it in GitHub Desktop.
creating table from array of json with d3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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> |
Hi @LevelbossMike, this is great, but I have two questions:
- 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.
- 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?
How do you manage table updates?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Great, thank you!