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.
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
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) {
...
}
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