D3.js drawing tables - Object.keys(), map()
Introduces how to create tables with D3.js.
For arrays
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>D3 Table</title>
<script src="https://d3js.org/d3.v7.min.js"></script>
</head>
<body>
<script>
var dataset = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[10, 11, 12],
];
d3.select("body")
.append("table")
.attr("border", "1") // Show border
.append("tbody")
.selectAll("tr")
.data(dataset)
.enter()
.append("tr")
.selectAll("td")
.data(function(row) { return row; })
.enter()
.append("td")
.text(function(d) { return d; });
</script>
</body>
</html>
For objects
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>D3 Table</title>
<script src="https://d3js.org/d3.v6.min.js"></script>
</head>
<body>
<script>
var dataset = [
{ "name": "A", "para1": 0, "para2": 5 },
{ "name": "B", "para1": 1, "para2": 6 },
{ "name": "C", "para1": 2, "para2": 7 },
{ "name": "D", "para1": 3, "para2": 8 },
{ "name": "E", "para1": 4, "para2": 9 }
]
var columns = Object.keys(dataset[0]);
var table = d3.select("body")
.append("table")
.attr("border", "1") // Show border;
table.append("thead")
.append("tr")
.selectAll("th")
.data(columns)
.enter()
.append("th")
.text(function(d) { return d; });
table.append("tbody")
.selectAll("tr")
.data(dataset)
.enter()
.append("tr")
.selectAll("td")
.data(function(row) {
return columns.map(function(column) {
return {column: column, value: row[column]};
})
})
.enter()
.append("td")
.text(function(d) { return d.value; });
</script>
</body>
</html>
Object.keys(dataset[0]) is a function that retrieves the keys of an object as an array.
var columns = Object.keys(dataset[0]);
To create the table header, extract the strings from the first row of dataset.
Object.keys({ "name": "A", "para1": 0, "para2": 5 })
Return result:
["name", "para1", "para2"]
Also, d3.entries() on line 40 is a function that extracts the keys and values of an object as an array.
When dataset is specified for an object in the data function,
.data(dataset)
the dataset data is passed one row at a time to the function argument as an object named row, as shown below.
.data(function(row) {
return columns.map(function(column) {
return {column: column, value: row[column]};
})
})
As a result, data is received by row and transformed into a shape such as {column: column name, value: value}.
[
{"column" : "name", "value" : "A"},
{"column" : "para1", "value" : 0},
{"column" : "para2", "value" : 5}
]