In this video tutorial, you will learn how to create a table from an array of objects in javascript.

Subscribe : https://www.youtube.com/channel/UCBwPlFFaigg5WA-Y1Iz-HUA

Source Code:


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

#js #javascript #html

How to Create Table From an Array of Objects in Javascript
16.20 GEEK