Reading time: 2 minutes
To create a simple table from an array of objects, follow the steps below:
First, create a file with the .html extension, where you’ll create a div with an associated ID to display the table with the data of the elements. The ID for the table within the HTML will be “tabla” as an example.
<div id="tabla">
Once you have the ID where you’ll build the table, create a file with the .js extension. In this file, you’ll develop the logic part.
Create a file named main.js as an example, then associate this file with the HTML as follows:
Inside the JavaScript file, declare and initialize the array of objects that you want to display in your table:
var objectArray = [
{
id: 1,
name: "DevCodeLight1",
},
{
id: 2,
name: "DevCodeLight2",
},
{
id: 3,
name: "DevCodeLight3",
}
];
Add the following method, which is triggered when the HTML document has been completely loaded and parsed:
document.addEventListener("DOMContentLoaded", function(event) {
});
Create a function to handle the logic for rendering our object table.
We’ll iterate over the data using a for loop, and for each element, we’ll perform the same rendering. In this case, we’ll access the attributes of each object, its ID and name. We’ll add the attributes within a table, using the <table></table> tags.
Finally, outside the loop, specify the ID of the element where you want to display the table of data.
function createObjectTable() {
var accumulator = "";
accumulator += "<table>" +
"<thead>" +
"<tr>" +
"<th>Id</th>" +
"<th>Name</th>" +
"</tr>" +
"</thead>" +
"<tbody>";
for (var i = 0; i < objectArray.length; i++) {
accumulator += "<tr>" +
"<td>" + objectArray[i].id + "</td>" +
"<td>" + objectArray[i].name + "</td>" +
"</tr>";
}
accumulator += "</tbody>" +
"</table>";
document.getElementById("tabla").innerHTML = accumulator;
}
Call this method from the previously created function, resulting in the following JavaScript: