skip to Main Content

I have a list of athlete names in JSON format from a fetch. Using for loop, I want to grab all the names under roster > athlete > name and then inserting them into dropdown menu.

But for some reason the loop is not working. If I take out the loop and just grab a single athlete, it worked. Maybe I got confused about arrays and objects?

JSON code

{
    "team": {
        "color": "000000",
        "country": "USA",
        "roster": [
            {
                "athlete": {
                    "name": "John Doe",
                    "age": 20
                }
            },
            {
                "athlete": {
                    "name": "Jane Doe",
                    "age": 21
                }
            },
            {
                "athlete": {
                    "name": "Jack Doe",
                    "age": 22
                }
            },
            {
                "athlete": {
                    "name": "Joe Doe",
                    "age": 23
                }
            }
        ]
    }
}

JS code

async function getAthletes() {

    const getPlayers = document.getElementById('getPlayers')

    await fetch('athlete.json', {
        method: 'GET'
    })
    .then((response) => response.json())
    .then(data => {

        const athletes = data.team.roster[0].athlete

        for(let i = 0; i < athletes.length; i++) {
            getPlayers.innerHTML += `<option value="${athletes[i].name}">${athletes[i].name}</option>`
        }
    }) 
}

HTML

<select id="getPlayers" data-category="Vote" data-action="click" data-label="Select Player">
    <option value="">Select player</option>
</select>

Hoping to get like this after the loop

<select id="getPlayers" data-category="pick" data-action="click" data-label="Select Player">
    <option value>Select player</option>
    <option value="John Doe">John Doe</option>
    <option value="Jane Doe">Jane Doe</option>
    <option value="Jack Doe">Jack Doe</option>
    <option value="Joe Doe">Joe Doe</option>
</select>

4

Answers


  1. Just look at what you’re doing semantically here:

    const athletes = data.team.roster[0].athlete
    

    You’re creating a variable called athletes and setting its value to an athlete. A single instance of something is not a list of something. In that operation you specify index 0 of the array. If you want to loop over the entire array, don’t use only one of its elements. Use the entire array:

    const athletes = data.team.roster;
    

    Then each element in the array would be like:

    {
      "athlete": {
        "name": "John Doe",
        "age": 20
      }
    }
    

    So referencing a value on it in the loop would be something like:

    athletes[i].athlete.name
    
    Login or Signup to reply.
  2. The athlete property is not the array, and has no .length. It is roster that is the array, which must be iterated. For instance:

    for (const {athlete: { name }} of data.team.roster) {
        getPlayers.innerHTML += `<option value="${name}">${name}</option>`;
    }
    
    Login or Signup to reply.
  3. You should grab team.roster off the data and loop over the values.

    Each value should have an athlete.name attribute.

    const playerSelect = document.getElementById('getPlayers');
    
    // Mock the fetch call
    const fetch = async (url, options) => Promise.resolve(({
      json: async () => Promise.resolve({
        "team": {
          "color": "000000",
          "country": "USA",
          "roster": [
            { "athlete": { "name": "John Doe", "age": 20 } },
            { "athlete": { "name": "Jane Doe", "age": 21 } },
            { "athlete": { "name": "Jack Doe", "age": 22 } },
            { "athlete": { "name": "Joe Doe",  "age": 23 } }
          ]
        }
      })
    }));
    
    async function getAthletes() {
      await fetch('athlete.json', { method: 'GET' })
        .then((response) => response.json())
        .then(({ team: { roster } }) => {
          roster.forEach(({ athlete: { name } }) => {
            // DOM manipulation, no hand-written HTML
            playerSelect.append(new Option(name, name));
          });
        });
    }
    
    getAthletes(); // Call the async function to populate the select
    <select id="getPlayers" data-category="Vote" data-action="click" data-label="Select Player">
      <option value="">Select player</option>
    </select>
    Login or Signup to reply.
  4. First of all from your JSON,data.team.roster is the array.
    So we have to iterate that array.

    JS Code

    async function getAthletes() {
    
        const getPlayers = document.getElementById('getPlayers')
    
        await fetch('athlete.json', {
            method: 'GET'
        })
        .then((response) => response.json())
        .then(data => {
    
            const rosters = data.team.roster
    
            for(let i = 0; i < rosters.length; i++) {
                getPlayers.innerHTML += `<option
           value="${rosters[i].athlete.name}">${rosters[i].athlete.name</option>`
            }
        }) 
    }
    

    For your other doubt yes u can iterate object also,but with for-in loop or for-each loop or for-of (not with normal FOR).
    Arrays can be looped using normal FOR & Foreach.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search