Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid undefined in object key with no value?

Tags:

javascript

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?

like image 429
Dillinger Avatar asked Nov 24 '25 02:11

Dillinger


1 Answers

I'd probably go for another check before accessing val:

if (key === 'unavailables' && val && val.length) 
{
    console.log("=> ", val[0]['id']);
}
like image 167
axelduch Avatar answered Nov 26 '25 16:11

axelduch