How to Create Table From an Array of Objects in Javascript

 
In this tutorial, you will learn how to create a table from an array of objects in javascript. Having a table with fixed values for heading, rows, and columns only requires the use of table, th, tr, and td tags.

But what if you want to generate a table dynamically when you don’t have a fixed set of values for heading, rows, and columns? Such a thing only happens when you want to pull data from the server and display it to the user in table format.

If your server is returning all the necessary details in the form of an array of objects, then surely we can use javascript to create a table from that array of objects.

We are not going to cover data fetching since that is out of the scope of this tutorial. We are only going to cover table creation using an array of objects.

In the following example, we have one button and one div element with id of table. div element does not have any child element. In the javascript file, we have an array of objects and upon click of a button, we want to utilize this array to generate a table and append that table to the div element.

Please have a look over the code example and steps given below for a detailed explanation.

HTML & CSS

  • We have 2 div elements and 1 button element in the HTML file. One of the div element is just a wrapper for the rest of the elements.
  • The inner text for the button element is “Get”.
  • The child div element has an id of the table because we will append our table to it.
  • We have done some basic styling using CSS and added the link to our style.css stylesheet inside the head element.
  • We have also included our javascript file script.js with a script tag at the bottom.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    
    <div>
        <button>Get</button>
        <div id="table"></div>
    </div>
    <script src="script.js"></script>
</body>
</html>
body {
    text-align: center;
}

div {
    display: inline-block;
}

button {
    display: inline-block;
    padding: 10px 20px;
}

#table {
    display: block;
    margin-top: 20px;
}

th, td {
    border: 1px solid black;
    padding: 5px;
}

Javascript

  • We have selected two elements button and div using the document.querySelector() method and stored them in btnGet and myTable variables respectively.
  • We have variable employees and it holds an array of objects.
  • We have variable headers and it holds an array of strings. These strings will be used as headers in our table.
  • We have attached the click event listener to the button element.
  • We are using document.createElement() method to create table and tr elements. The newly created elements are stored in table and headerRow variables.
  • We are looping through the headers array using the forEach() method. In the anonymous function, we are creating th element using a document.createElement() method and creating text node using document.createTextNode().  We are appending textNode to the header and later appending the header to headerRow.
  • Our header is ready, so we are appending it to the table.
  • We are looping through the employees array and repeating the same operation which we did for the header row, but this time we are using the td element instead of the th element because we need cells, not headers. We are appending each row to the table.
  • Finally, we are appending the entire table to the div element.
let btnGet = document.querySelector('button');
let myTable = document.querySelector('#table');


let employees = [
    { name: 'James', age: 21, country: 'United States' },
    { name: 'Rony', age: 31, country: 'United Kingdom' },
    { name: 'Peter', age: 58, country: 'Canada' },
    { name: 'Marks', age: 20, country: 'Spain' }
]

let headers = ['Name', 'Age', 'Country'];

btnGet.addEventListener('click', () => {
    let table = document.createElement('table');
    let headerRow = document.createElement('tr');

    headers.forEach(headerText => {
        let header = document.createElement('th');
        let textNode = document.createTextNode(headerText);
        header.appendChild(textNode);
        headerRow.appendChild(header);
    });

    table.appendChild(headerRow);

    employees.forEach(emp => {
        let row = document.createElement('tr');

        Object.values(emp).forEach(text => {
            let cell = document.createElement('td');
            let textNode = document.createTextNode(text);
            cell.appendChild(textNode);
            row.appendChild(cell);
        })

        table.appendChild(row);
    });

    myTable.appendChild(table);
});