How to put the first row in the CA to align thead <th> in the table and the rest go to tbody <td> with d3

I am trying to learn D3 by creating a table. The code below is what I still have.

Say that my TSV data has 3 columns, I want the first row (3 objects from the data) => to be in my section and the rest (the 4th object of my data) enter the tbody section

d3.text("test.tsv",  function(text) {
    var data = d3.tsv.parseRows(text);

var table = d3.select("body").append("table"), 
      thead = table.append("thead"),
      tbody = table.append("tbody");

 var hrows = thead.selectAll("tr")
      .data(data)
      .enter()
      .append("tr");



      var hcells = hrows.selectAll("th")
      .data(function(row) {
        return d3.range(Object.keys(row).length).map(function(column, i) {
          return row[Object.keys(row)[i]];
          });
        })
      .enter()
      .append("th")
      .text(function(d) { return d; });

// ============
      var rows = tbody.selectAll("tr")
      .data(data)
      .enter()
      .append("tr");


      var cells = rows.selectAll("td")
      .data(function(row) {
        return d3.range(Object.keys(row).length).map(function(column, i) {
          return row[Object.keys(row)[i]];
          });
        })
      .enter()
      .append("td")
      .text(function(d) { return d; });
 });
0
source share
1 answer

As Lars said in the comments, getting only the title bar in the title bar is just a matter of just having a lot of data in the data pool.

However, your nested data pooling is rather confusing and assumes that you cannot understand what your data is doing, so let it break:

, d3 (d3.selectAll("something").data(dataset)), , DOM. , ; , .

( ), . , , , , .

- . , d3.tsv.parseRows(text): , .

, d3.tsv.parse(text), d3.tsv(filename, function), , , . , , . - , - , .

var hrows = thead.selectAll("tr")
      .data(data[0]) //the first row of the data file
      .enter()
      .append("tr");

var hcells = hrows.selectAll("th")
      .data(function(row) { return row; }) //row is already an array
      .enter()
      .append("th")
      .text(function(d) { return d; });


var rows = tbody.selectAll("tr")
      .data(data.slice(1)) //a slice of the data array, starting from index 1
      .enter()
      .append("tr");

var cells = hrows.selectAll("td")
      .data(function(row) { return row; })
      .enter()
      .append("td")
      .text(function(d) { return d; });

(, ), , <th> <td>.

, :

  .data(function(row) {
    return d3.range(Object.keys(row).length).map(function(column, i) {
      return row[Object.keys(row)[i]];
      });

, , , (Object.keys(row).length), , (d3.range(number)), (array.map(function)). integer (column) (i, ), , .

, Javascript , , , row.

+3

All Articles