Home > Software design >  How to access JSON object in javascript?
How to access JSON object in javascript?

Time:07-07

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",
      }
    ],
    "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);
    }

CodePudding user response:

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>

CodePudding user response:

You first need to target Albums.Krezip and then iterate through Krezip like you've done before to access artist field.

If your variable data is the same as the Json you posted.

It would be : data.Albums.Krezip[i].artist

CodePudding user response:

your json

const json = {
  "Albums": {
    "Krezip": [
      {
        "artist":"Krezip",
        "title":"Days like this",
      }
     ]
  }
}

inside for loop

const albums = json.Albums // this is an array of albums

for(let key of Object.keys(albums)){
    const album = albums[key]
    // If this is an array then you might need to loop through them
    console.log(album[0])
}

CodePudding user response:

Replace:

const data = JSON.parse(request.responseText);

With:

const data = Object.values(JSON.parse(request.responseText).Albums)
                   .map(arr => arr[0]);

const request = { responseText: '{"Albums":{"Krezip":[{"artist":"Krezip","title":"Days like this"}],"Cure":[{"artist":"The Cure","title":"Wish"}]}}' };

const data = Object.values(JSON.parse(request.responseText).Albums)
                   .map(arr => arr[0]);
let option;
for (let i = 0; i < data.length; i  ) {
    option = document.createElement('option');
    option.text = data[i].artist;
    dropdown.add(option);
}
<select id="dropdown"></select>

CodePudding user response:

try this

for (const prop in data.Albums) {
  let item = data.Albums[prop];
  for (let i = 0; i < item.length; i  ) {
    option = document.createElement("option");
    option.text = item[i].artist;
   dropdown.add(option);
  }
}
  • Related