syntax.us Let the syntax do the talking
Blog Contact Posts Questions Tags Hire Me

Question:
In D3.js How To Build HTML Table with CSV?

I can use D3.js and a CSV file to drive creation of an HTML table.

This is a common scenario.

The list below describes some JavaScript-D3 steps I could follow to create an HTML table.
  • Study the parent page and decide on a location for the table
  • Create a D3 object for the parent
  • Example: var d3table_parent = d3.select('.zebra_it');
  • Create the table from the parent
  • Example: var d3table = d3table_parent.append('table');
  • Call d3.csv("/iris.csv") to create an array of objects named csv_a
  • Ask csv_a to drive a forEach-loop
  • Example: csv_a.forEach(function(row) { something; });
  • Inside the loop, append a tr-element to the table
  • Example: var d3row = d3table.append('tr');
  • Inside the loop, build an array from the row-object
  • Example1: var row_a = []; row_a.push(row.sepal_len); row_a.push(row.sepal_wid);
  • Example2: var row_a = []; for (key in row) {row_a.push(row[key])}
  • Inside the loop, append td-elements to the row
  • Example: row_a.forEach(function(el) {d3row.append('td');});
  • Join the td-elements with their data
  • Example: var d3td_hd = d3row.selectAll('td').data(row_a);
  • Fill the td-elements with their data
  • Example: d3td_hd.text(function(d) {return d;});
An example CSV file is at this URL: /iris.csv

The JavaScript I wrote from the above list is displayed below:

var d3table_parent = d3.select('.zebra_it');
var d3table        = d3table_parent.append('table');
d3.csv("/iris.csv", function(error, csv_a) {
  if (error) throw error;
  csv_a.forEach(function(row) {
    var d3row = d3table.append('tr');
    var row_a = [];
    for (key in row) {row_a.push(row[key])}
    row_a.forEach(function(el) {d3row.append('td');});
    var d3td_hd = d3row.selectAll('td').data(row_a);
    d3td_hd.text(function(d) {return d;});
  });
});
The hidden JavaScript which actually runs on this page is below this line:


The table created from the JavaScript is displayed below:

syntax.us Let the syntax do the talking
Blog Contact Posts Questions Tags Hire Me