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.
CodePudding user response:
You can loop through the array and for each element add a row to a newly forged table that will be added to the document at the end.
This is a demo:
let players = [
{name: 'Player1',score:10},
{name: 'Player2',score: 7},
{name: 'Player3',score:3}
];
const newTable = document.createElement("table");
newTable.innerHTML = "<thead><th>Player</th><th>Score</th></thead>";
for(player of players){
const newRow = document.createElement("tr");
const tdPlayer = document.createElement("td");
const tdScore = document.createElement("td");
tdPlayer.textContent = player.name;
tdScore.textContent = player.score;
newRow.appendChild(tdPlayer);
newRow.appendChild(tdScore);
newTable.appendChild(newRow);
}
const target = document.getElementById('target');
target.appendChild(newTable);
table{
border: solid 1px black;
}
table td{
border: solid 1px black;
}
<div id="target">
</div>
CodePudding user response:
You can use something like
<body>
<div >
<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>