How to check if a variable inside an object that's inside another object is set (js)?
<p>I'd like to do this:</p>

<pre><code>if(a.b.c) alert('c exists')   //produces error
if(a &amp;&amp; a.b &amp;&amp; a.b.c ) alert('c exists')   //also produces ReferenceError
</code></pre>

<p>The only way I know of to do this (EDIT: This apparently is the only way):</p>

<pre><code>if(typeof(a) != "undefined" &amp;&amp; a.b &amp;&amp; a.b.c) alert('c exists');
</code></pre>

<p>or some type of function like this...</p>

<pre><code>if(exists('a.b.c')) alert('c exists');
function exists(varname){
    vars=varname.split('.');
    for(i=0;i&lt;vars.length;i++){
       //iterate through each object and check typeof
    }
}
//this wont work with local variables inside a function
</code></pre>

<p><strong>EDIT: SOLUTION BELOW</strong>
(Credit to this thread by Felix, I just adapted it a little
 <a href="http://stackoverflow.com/questions/4676223/check-if-object-member-exists-in-nested-object">Check if object member exists in nested object</a>)</p>

<p>This works:</p>

<pre><code>if (typeof a != 'undefined' &amp;&amp; a.b &amp;&amp; a.b.c) alert('c exists')
</code></pre>

<p>But the best thing I found is to put it into a function. I use 2 different functions, one to get a variable deep in an object, and one just to check if its set. </p>

<pre><code>/**
 * Safely retrieve a property deep in an object of objects/arrays
 * such as userObj.contact.email
 * @usage var email=getprop(userObj, 'contact.email')
 *      This would retrieve userObj.contact.email, or return FALSE without
 *      throwing an error, if userObj or contact obj did not exist
 * @param obj OBJECT - the base object from which to retrieve the property out of
 * @param path_string STRING - a string of dot notation of the property relative to
 * @return MIXED - value of obj.eval(path_string), OR FALSE
 */
function getprop(obj, path_string)
{
    if(!path_string) return obj
    var arr = path_string.split('.'),
        val = obj || window;

    for (var i = 0; i &lt; arr.length; i++) {
        val = val[arr[i]];
        if ( typeof val == 'undefined' ) return false;
        if ( i==arr.length-1 ) {
            if (val=="") return false
            return val
        }
    }
    return false;
}

/**
 * Check if a proprety on an object exists
 * @return BOOL
 */
function isset(obj, path_string)
{
    return (( getprop(obj, path_string) === false ) ? false : true)
}
</code></pre>
