Help understanding dynamic destructuring - creating html dynamically from JSON data

I’m working on dynamically adding data to the page from an api endpoint, and I’m wondering what the best way to do it would be.

I’m trying to show the 10 most recent games for a specific team. Right now, I just have the html built out and am assigning the data.:

 <div id="firstGameSection">
        <div id="homeTeamSection"></div>
        <div id="awayTeamSection"></div>
    </div>
  const latestGame = () => {
      let homeTeamSection = document.getElementById('homeTeamSection')
          homeTeamSection.textContent = `${completedTenStonsGames[0].home_team.name} ${completedTenStonsGames[0].home_team_score}`
    }

But since I need to do this 10 times, I’m wondering what the best approach would be. It wouldn’t make sense to write the above 10 times and just change the index every time, but I’m not sure how to go about it.

Should I be creating the html within the javascript as well? How would you approach this?

Thanks!

I thought about doing a for each loop, but I wasn’t sure how I could also create the html for each of the 10 indexes. Am I able to do that within the method?

It is an array of objects, yes. I need to limit it to the ten most recent games still though, as of now, it’s returning all finished games. So realistically it’s just completed games right now.

Here’s what I currently have:



  const PISTONS_GAMES_URL = 'https://www.balldontlie.io/api/v1/games?seasons[]=2019&team_ids[]=9&per_page=82'

  fetch(PISTONS_GAMES_URL)
  .then((response) => {
    return response.json();
  })
  .then((stonsGamesJSON) => {
    //Set the JSON data for games to a variable
    const stonsGamesData = stonsGamesJSON.data

    //Sort pistons games to be in  order starting at beginning of the season
    const sortedStonsGames = stonsGamesData.sort((a,b) => a.id > b.id ? 1 : -1)
    console.log(sortedStonsGames)

    //Show pistons game that have already been played and reverse the order to show the most recent game first
    const completedTenStonsGames = sortedStonsGames.reverse().filter(games => games.status == 'Final')
    console.log(completedTenStonsGames)

    const latestGame = () => {
      let homeTeamSection = document.getElementById('homeTeamSection')
          homeTeamSection.textContent = `${completedTenStonsGames[0].home_team.name} ${completedTenStonsGames[0].home_team_score}`
    }

    latestGame()

  });

So should I be using === then?

I’m still a little confused about how to concatenate the html for each index, but I’ll look more into it.