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?

1

1 Answer 1

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/

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.