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 use of HTML table, th, tr, and td tags. But what if you want to generate table dynamically when you don’t have fixed set of values for heading, rows, and columns? Such thing only happen when you want to pull data from server.

If you server is returning all the necessary details in the form of array of object, 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 scope of this tutorial. We are only going to cover table creation using array of objects. HTML, CSS, and Javascript code is given below.

 

HTML:

<!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>

 

CSS:

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:

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);
});

 

 

  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •