you can do the trick without making any conditions, just by iterate through your object.
i made a plunker example , where i created a json file similar to yours , with and without items into unavailables array
this is the json:
[
{
"unavailables":[{"notes":"test1","start_datetime":"30/11/2015"},{"notes":"test2","start_datetime":"01/12/2015"}]
},
{
"unavailables":[{"notes":"test3","start_datetime":"03/12/2015"}]
},
{
"unavailables":[]
}
]
i have left empty ,the last "unavailables array", on purpose.
javascript, where i call the json file..
Here i get the json file and read it.
**I use two loops,
- the outer for the objects array
the inner for the unavailables arrays. there is no way to get into the unavailables loop if it is empty, so we dont get any error of requesting undefined variables.
var xhr = new XMLHttpRequest();
xhr.onload = function() {
if (xhr.status === 200) {
console.log('JSON Fired');
responseObject = JSON.parse(xhr.responseText);
console.log(responseObject);
//here i iterate though the main objects on the outer loop
responseObject.forEach(function(obj){
//now i iterate through the unavailables array of each object and get values.
obj.unavailables.forEach(function(unav,indx,arr){
var notes = unav.notes;
var start = unav.start_datetime;
console.log(notes,start)
});
});
}
};
xhr.open('GET', 'myjson.json', true);
xhr.send(null);
live on plunker: http://plnkr.co/edit/MzpbDa?p=info
see the results on the console of your browser.
hope helps,good luck.
responseand getunavailablesfrom itunavailablesproperty of the responseresponseis an array of objects whose elements containunavailablesproperty