0

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?

inorganik
  • 24,255
  • 17
  • 90
  • 114
  • There are plenty of other dupes such as http://stackoverflow.com/questions/4343028/in-javascript-test-for-property-deeply-nested-in-object-graph or http://stackoverflow.com/questions/6927242/whats-the-simplest-approach-to-check-existence-of-deeply-nested-object-property – epascarello May 05 '14 at 19:56

1 Answers1

0

Navigate safely to it. foo will evaluate to false in case you don't get all the way.

var foo = myObject.some && myObject.some.nested && myObject.some.nested.property;
if(foo)
    //use foo

http://jsfiddle.net/Y7LFp/

Johan
  • 35,120
  • 54
  • 178
  • 293