Search code examples
javascripthtmlarraysjavascript-objects

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

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