I'm trying to iterate an object like this:
0: Object
appointments: Array[2]
unavailables: Array[2]
0: Object
1: Object
book_datetime: "2015-10-22 02:46:23"
data: "0"
end_datetime: "2015-10-22 13:00:00"
hash: null
id: "21"
id_google_calendar: null
id_services: null
id_users_customer: null
id_users_provider: "87"
is_unavailable: "1"
notes: "Nessuna"
resource_id: "0"
start_datetime: "2015-10-22 12:00:00"
__proto__: Object
length: 2
__proto__: Array[0]
__proto__: Object
1: Object
appointments: Array[1]
unavailables: Array[0]
length: 0
__proto__: Array[0]
__proto__: Object
length: 2
__proto__: Array[0]
in this way:
$.each(response, function(_, obj)
{
$.each(obj, function(key, val)
{
if (key === 'unavailables')
{
console.log("=> ", val[0]['id']);
}
});
});
Now all working fine but how you can see the second array contain unavailables length = 0, when the loop is on here I get
Cannot read property 'id' of undefined
How can avoid this? There is a method that check if the current key has contain value or not?
I'd probably go for another check before accessing val:
if (key === 'unavailables' && val && val.length)
{
console.log("=> ", val[0]['id']);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With