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
Just look at what you’re doing semantically here:
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:Then each element in the array would be like:
So referencing a value on it in the loop would be something like:
The
athlete
property is not the array, and has no.length
. It isroster
that is the array, which must be iterated. For instance:You should grab
team.roster
off thedata
and loop over the values.Each value should have an
athlete.name
attribute.First of all from your JSON,data.team.roster is the array.
So we have to iterate that array.
JS Code
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.