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 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.
Share edited Jun 7, 2022 at 9:24 Donald Duck is with Ukraine 8,91223 gold badges79 silver badges102 bronze badges asked Jun 7, 2022 at 7:31 RaptorRVRaptorRV 651 silver badge10 bronze badges 2- Loop over the data and create a row for each object where each cell is the value of a property. – Andy Commented Jun 7, 2022 at 7:36
- 2 stackoverflow./questions/72380775/… – Andy Commented Jun 7, 2022 at 7:40
4 Answers
Reset to default 6You 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>
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>
Based on Diego D's answer, I made a more scalable (extensible) function (primarily for my needs).
const players = [
{name: 'Player1', score: 10, id:'aaa', address: 'usa'},
{name: 'Player2', score: 7, id:'bbb', address: 'mars'},
{name: 'Player3', score: 3, id:'ccc', address: 'jupyter'},
];
const fullHeaders = Object.keys(players[0]); //use full header
const selectedHeaders = ['name', 'score']; //or filter as needed
const table1 = makeTable(fullHeaders, players);
const table2 = makeTable(selectedHeaders, players);
function makeTable(headers, players, target = document.body) {
const newTable = document.createElement("table");
const thead = document.createElement("thead");
for(header of headers) {
const th = document.createElement("th");
th.textContent = header;
thead.appendChild(th);
}
newTable.appendChild(thead);
for(player of players) {
const newRow = document.createElement("tr");
for(header of headers) {
const td = document.createElement("td");
td.textContent = player[header];
newRow.appendChild(td);
}
newTable.appendChild(newRow);
}
return target.appendChild(newTable);
}
After having provided this answer to a similar question that was very quickly closed (due to "lack of effort" on the questioner's part) I would like to present it here again in the hope that it might still be helpful to someone.
There are many ways of creating an HTML table from an array of objects. The answers given so far to this question seem to be relatively verbose or specific to the given object structure.
As a more generic way of doing it with a minimum of script effort I would suggest the following function:
function arr2tbl(array){
// row: creates html for a single table row:
const row=(obj,what,cell)=>`<tr>${Object[what](obj).map(k=>`<t${cell}>${k}</t${cell}>`).join("")}<tr>`;
return row(array[0],"keys","h") // heading row
+ array.map(o=>row(o,"values","d")).join(""); // table body
}
The snippet below shows this function in action:
function arr2tbl(array){
// row: creates html for a single table row:
const row=(obj,what,cell)=>`<tr>${Object[what](obj).map(k=>`<t${cell}>${k}</t${cell}>`).join("")}<tr>`;
return row(array[0],"keys","h") // heading row
+ array.map(o=>row(o,"values","d")).join(""); // table body
}
const arr = [{name: 'Player1',score:10},
{name: 'Player2',score: 7},
{name: 'Player3',score:3}],
records = [
{
artist: 'Miles Davis',
album: 'Kind of Blue',
label: 'Columbia',
year: 1959,
genre: 'Jazz'
},
{
artist: 'Ralph Stanley',
album: 'Old Home Place',
label: 'Rebel',
year: 1976,
genre: 'Bluegrass'
},
{
artist: 'Bad Religion',
album: 'No Control',
label: 'Epitaph',
year: 1989,
genre: 'Punk Rock'
},
{
artist: 'John Coltrane',
album: 'A Love Supreme',
label: 'Impulse!',
year: 1965,
genre: 'Jazz'
},
{
artist: 'Descendants',
album: 'Milo Goes to College',
label: 'New Alliance',
year: 1982,
genre: 'Punk Rock'
},
{
artist: 'Charles Mingus',
album: 'Town Hall Concert',
label: 'Jazz Workshop',
year: 1959,
genre: 'Jazz'
},
{
artist: 'Tony Rice',
album: 'Manzanita',
label: 'Rounder',
year: 1979,
genre: 'Bluegrass'
},
{
artist: 'Ornette Coleman',
album: 'The Shape of Jazz to Come',
label: 'Atlantic',
year: 1959,
genre: 'Jazz'
},
{
artist: 'Joni Mitchell',
album: 'Blue',
label: 'Reprise',
year: 1971,
genre: 'Rock'
},
{
artist: 'Pat Martino',
album: 'El Hombre',
label: 'Prestige',
year: 1967,
genre: 'Jazz'
},
{
artist: 'Roy Haynes',
album: 'Out of the Afternoon',
label: 'Impulse!',
year: 1962,
genre: 'Jazz'
},
{
artist: 'Neil Young',
album: 'Harvest',
label: 'Reprise',
year: 1972,
genre: 'Rock'
},
],
[one,two,three] = document.querySelectorAll('table');
one.innerHTML = arr2tbl(arr);
two.innerHTML = arr2tbl(records.filter(record => record.genre === 'Jazz'))
fetch("https://jsonplaceholder.typicode./posts").then(r=>r.json()).then(arr=>
three.innerHTML=arr2tbl(arr))
table {border-collapse:collapse;}
td,th {padding: 4px;
border: 1px solid grey;
vertical-align: top;
text-align: left;}
.num2 td:nth-child(2) {text-align:right}
<h2>Table 1</h2>
<table class="num2"></table>
<h2>Table 2</h2>
<table></table>
<h2>Table 3</h2>
<table class="num2"></table>
The function arr2tbl()
generates a simple HTML string resulting in a table that will show all the objects of the given array of objects. The property names of the objects will be the column names.
The above function will work for any array of objects in which the contained objects are "simple" in structure, i . e. their properties are string or numeric values and do not contain further objects or arrays in themselves.
As the function is agnostic to the structure of the objects in the array it can be applied to any array without any changes. The second and third tables in my snippet demonstrate this.