Issue
I want to select the "artist"
and put it in the selector and I want to keep it in vannila javascript.
I thought this would select the artist from my JSON file.
option.text = data[i].artist;
My JSON
{
"Albums": {
"Krezip": [
{
"artist":"Krezip",
"title":"Days like this",
"tracks": [
{
"title":"Lost without you",
"src":"https://www.youtube.com/embed/zazrmePIL9Y",
"dur":"3:35"
},
{
"title":"I would stay",
"src":"https://www.youtube.com/embed/kfrGFGHU6YA",
"dur":"4:04"
}
]
}
],
"Cure": [
{
"artist":"The Cure",
"title":"Wish",
}
]
}
}
And my javascript
const data = JSON.parse(request.responseText);
let option;
for (let i = 0; i < data.length; i++) {
option = document.createElement('option');
option.text = data[i].artist;
dropdown.add(option);
}
Solution
Your loop won't work because your parsed data is an object which doesn't have a length
property.
If you just want the artist names to populate a dropdown use Object.keys
to get an array of artist names and iterate over it. You can use a loop as in your example, or for...of as I've done here - a working example using an existing select
element (since I don't know what dropdown
does).
const select = document.querySelector('select');
const json = '{"Albums": {"Krezip": [{"artist":"Krezip","title":"Days like this"}],"Cure": [{"artist":"The Cure","title":"Wish"}]}}';
const data = JSON.parse(json);
// `Object.keys` returns an array of artists
const artists = Object.keys(data.Albums);
for (const artist of artists) {
const option = document.createElement('option');
option.textContent = artist;
option.value = artist;
select.appendChild(option);
}
<select>
<option disabled selected>Choose an artist</option>
</select>
Alternatively, if you want both the artist name and the album information available in the loop, use Object.entries
. Destructure the artist name (key) and the album list (value), and use artist
to update your drop-down list. You can then also do something else with the album array should you wish.
const select = document.querySelector('select');
const json = '{"Albums": {"Krezip": [{"artist":"Krezip","title":"Days like this"}],"Cure": [{"artist":"The Cure","title":"Wish"}]}}';
const data = JSON.parse(json);
// `Object.entries` returns an array of key/value pairs
const entries = Object.entries(data.Albums);
// We can destructure the key/value pairing and call
// them something more meaningful. Then just use that data
// to create the options
for (const [artist, albums] of entries) {
const option = document.createElement('option');
option.textContent = artist;
option.value = artist;
select.appendChild(option);
console.log(JSON.stringify([artist, albums]));
}
<select>
<option disabled selected>Choose an artist</option>
</select>
Answered By - Andy Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.