How to access JSON array elements in javascript?

I need help accessing objects from a JSON array response from an API. I need to access “img_src” below I have attached an image of the JSON array and what i have tried thus far.

The JSON Array Response:

This javascript code is how I am accessing the objects:

function useApiData(data){
      document.querySelector("#content").innerHTML += data.photos.array
}

Hi,

From what you’ve posted, it looks like data.photos will give you an array of all your photos. You can then either access the img_src property of a specific photo (e.g. data.photos[0].img_src), or iterate over all of the photos and access each img_src in turn

data.photos.forEach((photo) => { console.log(photo.img_src); });
1 Like

Hi @michaelamay1, the is no array property on data.photos, it is the array – the logs on your screenshot are just telling you the type. You can access elements by index using the brackets notation, and then get the img_src property of that element like so:

// Get the first element's img_src
var first = data.photos[0]

if (first) {
  console.log(first.img_src)
}

// Iterate over all img_src's
for (var i  = 0; i < data.photos.length; i++) {
   console.log(data.photos[i].img_src)
}

If you want to append all those values to the #content element, another good option would be to first map() the array elements to their img_srcs first:

var sources = data.photos.map(function (photo) {
  return photo.img_src
})

document.querySelector("#content").innerHTML = sources.join('<br>')

(x-post)

1 Like

I found a simple coding trick is to copy the data that is coming from the API from the console.log and past it directly into javascript code. The only thing you might have to do if fix the array by deleting some brackets if my memory is correct. (I’m getting old)

Thank you, James! Your answer was really helpful.

Thank you! Your answer was also really helpful.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.