I am attempting to generate a table using D3.js along with a JSON file.
The dataset comprises six columns: code, name, unit, value, target, and norm. The objective is to display only three of them (name, target, and value) in the table. My intention is to utilize the values from the [code] and [norm] columns to define the "id" and the "class".
Below is the foundational code that I am employing. This code effectively creates the table itself but encounters issues when it comes to identifying "id" and "class":
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'];
var table1 = d3.select('#table').append('table');
var thead = table1.append('thead');
var tbody = table1.append('tbody');
// adding the header row
thead.append('tr')
.selectAll('th')
.data(["Name", "Target", "Value"])
.enter()
.append('th')
.text(function(column) {
return column;
});
// generate a row for each object in the data
var rows = tbody.selectAll('tr')
.data(data)
.enter()
.append('tr');
// create a cell for each column in every row
var cells = rows.selectAll('td')
.data(function(row) {
return columns.map(function(column) {
return {
column: column,
value: row[column]
};
});
})
.enter()
.append('td')
.html(function(d) {
return d.value;
});
});
My intended output for the table structure is provided below, where the JSON attributes of [code] are utilized as the "id" and [norm] serves as the "class". I have faced challenges in utilizing data elements at the cell level that are not used for populating the table's data fields. How can this be achieved?
<div id="table">
<table>
<thead>
<tr>
<th>Name</th>
<th>Target</th>
<th>Value</th>
</tr>
</thead>
<tbody>
<tr>
<td id="100" class="alert">A</td>
<td>0.75</td>
<td>0.6</td>
</tr>
<tr>
<td id="106" class="danger">B</td>
<td>0.75</td>
<td>0.6</td>
</tr>
<tr>
<td id="112" class="ok">C</td>
<td>0.75</td>
<td>0.9</td>
</tr>
</tbody>
</table>
</div>