score:0

Accepted answer

In the columns mapping for the tds, you can add a couple more keys as id and class:

i.e.

var columns = ['name', 'target', 'value'], column_id = 'code', column_class = 'norm';
 ....   
 ....

return columns.map(function(column) {
            return {
              column: column,
              value: row[column],
              id: row[column_id],
              class: row[column_class]
            };
          });

And add it to the tds as follows:

.attr('id', function(d) { return d.column === 'name' ? d.id : null; })
.attr('class', function(d) { return d.column === 'name' ? d.class : null; })

Here's a snippet combining all of the above:

 var data = [{
    "code": 100,
    "name": "A",
    "unit": 12,
    "value": 0.6,
    "target": 0.75,
    "norm": "alert"
  }, {
    "code": 106,
    "name": "B",
    "unit": 12,
    "value": 0.6,
    "target": 0.75,
    "norm": "danger"
  }, {
    "code": 112,
    "name": "C",
    "unit": 12,
    "value": 0.9,
    "target": 0.75,
    "norm": "ok"
  }];

  var columns = ['name', 'target', 'value'], column_id = 'code', column_class = 'norm';
  var table1 = d3.select('#table').append('table');

  var thead = table1.append('thead');
  var tbody = table1.append('tbody');

  // append the header row
  thead.append('tr')
    .selectAll('th')
    .data(["Name", "Target", "Value"])
    .enter()
    .append('th')
    .text(function(column) {
      return column;
    });

  // create a row for each object in the data
  var rows = tbody.selectAll('tr')
    .data(data)
    .enter()
    .append('tr');

  // create a cell in each row for each column
  var cells = rows.selectAll('td')
    .data(function(row) {
      return columns.map(function(column) {
        return {
          column: column,
          value: row[column],
          id: row[column_id],
          class: row[column_class]
        };
      });
    })
    .enter()
    .append('td')
    .attr('id', function(d) { return d.column === 'name' ? d.id : null; })
    .attr('class', function(d) { return d.column === 'name' ? d.class : null; })
    .html(function(d) {
      return d.value;
    });
<script src="https://d3js.org/d3.v4.min.js"></script>


<div id="table">

</div>

Hope this helps. :)


Related Query