I'm working with javascript objects that have nested properties I need to test for, like
myObject = { 'some' : { 'nested' : { 'property' : { 'foo' : 'bar' } } } ... } The trouble is myObject.some might not exist, nor myObject.some.nested, and so on. So to test for the existence of myObject.some.nested.property.foo I have to do this:
if (myObject.some) { if (myObject.some.nested) { if (myObject.some.nested.property) { if (myObject.some.nested.property.foo) { // do something with myObject.some.nested.property.foo here } } } } because if I do if (myObject.some.nested.property.foo) and one of the parent properties doesn't exist, it throws the error:
TypeError: 'undefined' is not an object (evaluating 'myObject.some.nested.property.foo') Is there a better way to test for nested properties without using so many if statements?