d3.object.array.table.201702201857

I created a table from object array in d3.js.

by ytyaru

HTML

<script src="http://d3js.org/d3.v4.min.js"></script>
<table id="NameList">
  <thead></thead>
  <tbody></tbody>
</table>
<table id="License">
  <tr><th>Library</th><th>License</th><th>Copyright</th></tr>
  <tr><th><a href="https://d3js.org/">d3.js</a></th><th><a href="https://opensource.org/licenses/BSD-3-Clause">BSD-3-Clause</a></th><th><a href="https://github.com/d3/d3/blob/master/LICENSE">Copyright 2010-2016 Mike Bostock</a></th></tr>
</table>

CSS

#License {
  font-size: 10px;
  margin-top: 30px;
}

JavaScript

var objs = [
  {"id": 0, "name": "木村", "age": 25},
  {"id": 1, "name": "谷口", "age": 12},
  {"id": 2, "name": "長澤", "age": 53}];
var table = d3.select("body").insert("table",":first-child");
var thead = table.append("thead");
var tbody = table.append("tbody");
tbody.select("tbody").data(objs).enter().each(function(d,j){createTable(d);});

function createTable(obj)
{
tbody.selectAll("tr")
  .data(d3.entries(obj))
  .enter()
  .append("tr")
  .append("th").text(function(d){return d.key;});
tbody.selectAll("tr")
  .append("td")
  .text(function(d){return d.value;});  
}