I have a JSON have the following data:
{
"results":[
{
"name":"Sydney Showboats",
"photos":[
{
"photo_reference":"Pic062"
}
]
},
{
"name":"Blue Line Cruises"
},
{
"name":"Rhythmboat Cruises",
"photos":[
{
"photo_reference":"Pic678"
}
]
},
{
"name":"Flying Fish Restaurant & Bar",
"photos":[
{
"photo_reference":"Pic345"
}
]
}
],
"status":"OK"
}
I'm trying to loop through this JSON to display every name value in the .name div and every image in the .photo div:
$.getJSON(jsonPlacesUrl, function(data) {
$.each(data.results, function(index){
$('.name').html('<p>' + data.results[index].name + '</p>');
$('.photo').html('<img src="' + data.results[index].photos[0].photo_reference + '.jpg">');
})
});
It works fine with the name value and works fine with the first image too. However, since there is no "photos" property in the second object, the script stops because of an
Uncaught TypeError: Cannot read property '0' of undefined.
So is there a way to either: Delete the objects which do not have the photos object nested inside? Use a more complex loop to iterate through the JSON and store every image available? Any possible solution allowing me to display every image available dynamically?
If anyone can enlighten me it would be gratefully appreciated!