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
Just look at what you’re doing semantically here:
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:
Then each element in the array would be like:
So referencing a value on it in the loop would be something like:
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:
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 withElement#append
.