types - JavaScript: Checking if an object field is undefined without checking if the object is undefined -


my ivr app receives business data in form of js objects , arrays. example, name of 1 of our customers accessed follows:

customerdata.customerlist[customerindex].customername 

now, in cases, customername undefined, because entire object undefined. right now, in order catch that, have nested logic checks each level being undefined, before checking last:

if (typeof customerdata != 'undefined' &&   typeof customerdata.customerlist &&   typeof customerdata.customerlist[customerindex] != 'undefined' &&   typeof customerdata.customerlist[customerindex].customername != 'undefined') {   //do awesome customer name, here } 

is there easier (cleaner?) way accomplish this, without having check each field on object?

thanks.

you need write first typeof ensure customerdata has been declared. after that, can skip testing undefined upto level wish

((customerdata || {}).customerlist || [])[customerindex] !== undefined 

Comments