I have some JSON data which is an array of objects. Inside the objects there's some string properties but also array properties.
I'm trying to display the array properties stacked with each array index result underneath other as opposed to side by side.
I'm not sure how to do this inside a table element.
I'd appreciate any help.
Thanks.
HTML
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>GTP</title>
</head>
<body>
<div id="players"></div>
<script type="text/javascript" src="gtp.js"></script>
</body>
</html>
JS
// Fetch players
function fetchPlayers(api) {
fetch(api)
.then(resp => resp.json())
.then(players => {
displayPlayers(players);
})
.catch((err) => {
console.log(err);
})
}
fetchPlayers('players.json');
// Display players
const displayPlayers = (players) => {
// Players HTML container
let playersElement = document.getElementById('players');
let playersContent = '';
playersContent += '<ul>';
const playersList = players.players;
const player = playersList[Math.floor(Math.random() * playersList.length)];
console.log(player);
const playerDetails = () => {
playersContent += '<tr>';
playersContent += `<td>${player.years}</td>`;
playersContent += `<td>${player.teams}</td>`;
playersContent += `<td>${player.apps}</td>`;
playersContent += `<td>${player.gls}</td>`;
playersContent += '</tr>';
}
playersContent += `<table>
<tr>
<th>Years</th>
<th>Team</th>
<th>Apps</th>
<th>(Gls)</th>
</tr>`
playerDetails();
`</table>`;
playersContent += '</ul>';
playersElement.innerHTML = playersContent;
}
JSON
{
"players": [
{
"id": 0,
"name": "Michael Owen",
"position": "Striker",
"years": ["1996-2004", "2004-2005", "2005-2009", "2009-2012", "2012-2013"],
"teams": ["Liverpool", "Real Madrid", "Newcastle United", "Manchester United", "Stoke City"],
"apps": ["216", "36", "71", "31", "8"],
"gls": ["118", "13", "26", "5", "1"]
},
{
"id": 1,
"name": "Robbie Savage",
"position": "Midfielder",
"years": ["1993-1994", "1994-1997", "1997-2002", "2002-2005", "2005-2008"],
"teams": ["Manchester United", "Crewe Alexandre", "Leicester City", "Birmingham City", "Blackburn Rovers", "Derby Country", "Brighton & Hove Albion (loan)"],
"apps": ["0", "77", "172", "82", "76", "124", "6"],
"gls": ["0", "10", "8", "11", "1", "7", "0"]
}
]
}