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.
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
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:
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)