Reputation: 1903
I'm trying to iterate over unavailable
(s) object that are returned by an ajax request. Now in some case the unavailable
property object could be only with one element or 0 element. I've created this code:
$.each(response.unavailables, function(index, unavailable)
{
var notes = unavailable.notes;
var start = start = unavailable.start_datetime;
var end = unavailable.end_datetime;
var data = unavailable;
//other stuff. ..
});
but I get:
Cannot read property length of undefined
This is the structure of my response variable:
Upvotes: 0
Views: 808
Reputation: 4671
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 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.
Upvotes: 1
Reputation: 103338
You can use a nested loop and check that the unavailables
array in each loop contains data:
$.each(response, function(index, r)
{
if (r.unavailables
&& r.unavailables.length){
$.each(r.unavailables, function(index, unavailable)
{
var notes = unavailable.notes;
var start = start = unavailable.start_datetime;
var end = unavailable.end_datetime;
var data = unavailable;
//other stuff. ..
});
}
});
Upvotes: 2