How to Create a Custom HTML Table from a JavaScript Array?

Estimated read time 1 min read

Here’s an example of how you can create a custom HTML table from a JavaScript array:

let data = [
  { name: "John Doe", age: 25, city: "New York" },
  { name: "Jane Doe", age: 30, city: "London" },
  { name: "Jim Brown", age: 35, city: "Paris" }
];

let table = document.createElement("table");

let header = table.createTHead();
let headerRow = header.insertRow();

let headers = Object.keys(data[0]);
headers.forEach(function(header) {
  let cell = headerRow.insertCell();
  cell.innerHTML = header;
});

let body = table.createTBody();
data.forEach(function(rowData) {
  let row = body.insertRow();
  headers.forEach(function(header) {
    let cell = row.insertCell();
    cell.innerHTML = rowData[header];
  });
});

document.body.appendChild(table);

This code creates a table with headers taken from the keys of the first object in the data array, and populates the rows with the corresponding values. The resulting table can be styled with CSS to your liking.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply