In this tutorial, we will create a JavaScript function that takes an array of objects as input and dynamically generates an HTML table with the data. The table will have a header row with column names and a row for each object in the array, with the data populated in the corresponding columns.
Start by creating an HTML file with a container element where the table will be inserted:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Create HTML Table from Array of Objects</title>
</head>
<body>
<div id="table-container"></div>
<script src="script.js"></script>
</body>
</html>
Next, create a JavaScript file named ‘script.js’ and write the function createTableFromObjects
:
script.js
function createTableFromObjects(data) {
const table = document.createElement('table');
const headerRow = document.createElement('tr');
// Create table header row
const keys = Object.keys(data[0]);
for (const key of keys) {
const headerCell = document.createElement('th');
headerCell.textContent = key;
headerRow.appendChild(headerCell);
}
table.appendChild(headerRow);
// Create table data rows
for (const obj of data) {
const dataRow = document.createElement('tr');
for (const key of keys) {
const dataCell = document.createElement('td');
dataCell.textContent = obj[key];
dataRow.appendChild(dataCell);
}
table.appendChild(dataRow);
}
return table;
}
This function first creates a table element and a header row element. It then iterates through the keys of the first object in the input array to create header cells with column names. Next, it loops through the input array, creating a table row for each object and populating the row with data cells corresponding to each key-value pair in the object. Finally, it returns the generated table element.
Now, let’s create a sample array of objects and call the createTableFromObjects
function:
const dataArray = [
{ id: 1, name: 'John', age: 30 },
{ id: 2, name: 'Jane', age: 28 },
{ id: 3, name: 'Doe', age: 45 },
];
const table = createTableFromObjects(dataArray);
To insert the generated table into the HTML document, select the container element and append the table as a child:
const tableContainer = document.getElementById('table-container');
tableContainer.appendChild(table);
After running this code, an HTML table will be dynamically generated with a header row containing the column names “id”, “name”, and “age”, and three data rows corresponding to the objects in the dataArray.
You can now use this function to easily create tables from various data sources in your projects.