Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to create an HTML table from an array of objects?

I need to generate a table from an array of objects.

For example, the array is:

let arr = [{name: 'Player1',score:10},
{name: 'Player2',score: 7},
{name: 'Player3',score:3}]

And the HTML output should be:
| Name| Score |
| ——– | ————– |
| Player1| 10|
| PLayer2| 7 |
|Player3| 3|

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I could not think of a way to achieve this through vanilla JS.
Also, after the table is created, how will I apply CSS to it?

Any help would be appreciated.

>Solution :

You can use something like

<body>
<div class="main-container">
    <table>
        <thead>
            <tr>
                <th>player</th>
                <th>score</th>
            </tr>
        </thead>
        <tbody></tbody>
    </table>
</div>
<script>
    const data = [{ name: 'Player 1', score: 10 },
    { name: 'Player 2', score: 7 },
    { name: 'Player 3', score: 3 }]

    const table = document.querySelector('tbody')
    data.forEach((item) => {
        table.innerHTML = table.innerHTML + `<tr>
                <td>${item.name}</td>
                <td>${item.score}</td>
            </tr>`
    })
</script>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading