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
                }
            }
        ]
    }
}

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>

3

Answers


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

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

    ou’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 main issue is that you were trying to index the athlete, which is not the array. The roster is the array. You also had some mixed up use of async/await. This might be helpful:

    async function getAthletes() {
      const getPlayers = document.getElementById('getPlayers')
      const response = await fetch('athlete.json');
      const data = await response.json();
      const roster = data.team.roster;
      for (let i = 0; i < roster.length; i++) {
        getPlayers.innerHTML += `<option value="${roster[i].athlete.name}">${roster[i].athlete.name}</option>`
      }
    }
    
    Login or Signup to reply.
  3. A simpler method in this case is to use Array#map to create an array of options, which can be added to the select element with Element#append.

    const data={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}}]}};
    const getPlayers = document.getElementById('getPlayers');
    
    getPlayers.append(...data.team.roster.map(o => new Option(o.athlete.name)));
    <select id="getPlayers" data-category="Vote" data-action="click" data-label="Select Player">
        <option value="">Select player</option>
    </select>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search