Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

My IVR app receives business data in the form of JS objects and arrays. For example, the name of one of our customers is accessed as follows:

customerData.customerList[customerIndex].customerName

Now, in some cases, customerName is undefined, because the entire object is undefined. Right now, in order to catch that, I have some nested logic that checks each level for being undefined, before finally checking the last:

if (typeof customerData != 'undefined' &&
  typeof customerData.customerList &&
  typeof customerData.customerList[customerIndex] != 'undefined' &&
  typeof customerData.customerList[customerIndex].customerName != 'undefined')
{
  //do something awesome with customer name, here
}

Is there an easier (cleaner?) way to accomplish this, without having to check each field on the object?

Thanks.

like image 279
IVR Avenger Avatar asked Mar 09 '26 00:03

IVR Avenger


2 Answers

You need to write the first typeof to ensure that customerData has been declared. After that, you can skip testing for undefined upto any level you wish

((customerData || {}).customerList || [])[customerIndex] !== undefined
like image 127
Imran Avatar answered Mar 10 '26 14:03

Imran


I know this works, but would venture to guess there will be some objections... which I'd love to hear:

var customerName = function(){
   try{ return customerData.customerList[customerIndex].customerName; }
   catch(e){ return null; }
};
if (customerName) {
   ...
}
like image 44
Darnell Avatar answered Mar 10 '26 13:03

Darnell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!