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