Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if object within object exists

It seems that the following technique for checking the existence of an object member produces an error because the 'bar' parent object hasn't been declared before the check, which means I either have to declare it before the check or use two 'typeof' expressions, either of which would be excess code:

var foo = {},
    newVal = (typeof foo.bar.myVal !== 'undefined' ? foo.bar.myVal : null );

Error: foo.bar is undefined

So, how do you check if a member within an undeclared object exists without producing an error?

I love javascript, but sometimes...

like image 541
Steve Avatar asked Jul 01 '11 12:07

Steve


Video Answer


2 Answers

It can be done simply using the code below:

var newVal = (foo && foo.bar && typeof foo.bar.myVal !== 'undefined') ? foo.bar.myVal : foo.bar.myVal

A property is null or undefined, it will be evaluated as false so the above code will only process up to the first 'false' statement.

like image 76
Dino Gambone Avatar answered Oct 20 '22 17:10

Dino Gambone


var newVal = ('foo' in window && // could be typeof foo !== 'undefined' if you want all scopes
             'bar' in foo &&
             'myVal' in foo.bar) ? foo.bar.myVal : null;

To be fair to javascript, that reads almost like natural language.

like image 45
davin Avatar answered Oct 20 '22 18:10

davin