'How can I access fetched data with multiple layers?
I need help trying to access the data the is fetched from an API? The only thing I can do is game.results which I show lower. Everything else I try just outputs "undefined". I'm not sure what else to try that is why I am asking because I have runout of ways to fix this.
function showGames()
{
const options = {
method: 'GET',
headers: {
'X-RapidAPI-Host': 'sportspage-feeds.p.rapidapi.com',
'X-RapidAPI-Key': '<KEY>'
}
};
let url = 'https://sportspage-feeds.p.rapidapi.com/games?league=NBA&date=2022-04-28';
fetch(url, options)
.then(res => {
return res.json();
})
.then((data) => {
const games = data;
let game = games;
let result = `<h2> NBA GAMES</h2>`;
console.log(game.results);
for(let i = 0; i < game.length; i++)
{
thisGame = game[i];
result += `
<div>
<h1>${game.results.summary}</h1>
</div>
`;
}
document.getElementById("games").innerHTML = result;
});
}
window.onload=showGames();
This is what one of the outputs of data.results looks like. I'm not sure how I can access the data in here like summary. I've tried using game.results.summary but it just outputs undefined.
[ { schedule: { date: '2022-04-28T23:00:00.000Z', tbaTime: false },
summary: 'Philadelphia 76ers @ Toronto Raptors',
details:
{ league: 'NBA',
seasonType: 'postseason',
season: 2021,
conferenceGame: true,
divisionGame: true },
status: 'final',
teams: { away: [Object], home: [Object] },
lastUpdated: '2022-04-29T01:38:41.138Z',
gameId: 284279,
venue:
{ name: 'Scotiabank Arena',
city: 'Toronto',
state: 'ON',
neutralSite: false },
odds: [ [Object] ],
scoreboard:
{ score: [Object],
currentPeriod: 4,
periodTimeRemaining: '0:00' } },
Solution 1:[1]
This statement in your loop:
game = game[i];
overwrites the array game and breaks the whole thing. You need a variable to use in the loop that is separate from the game array:
let thisGame = game[i];
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Pointy |
