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 acplish this, without having to check each field on the object?
Thanks.
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 acplish this, without having to check each field on the object?
Thanks.
Share Improve this question edited Apr 29, 2011 at 18:35 Alex K. 176k32 gold badges274 silver badges296 bronze badges asked Apr 29, 2011 at 18:30 IVR AvengerIVR Avenger 15.5k13 gold badges49 silver badges60 bronze badges2 Answers
Reset to default 6You 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) {
...
}