I'd like to do this:
if(a.b.c) alert('c exists')   //produces error
if(a && a.b && a.b.c ) alert('c exists')   //also produces ReferenceError
The only way I know of to do this (EDIT: This apparently is the only way):
if(typeof(a) != "undefined" && a.b && a.b.c) alert('c exists');
or some type of function like this...
if(exists('a.b.c')) alert('c exists');
function exists(varname){
    vars=varname.split('.');
    for(i=0;i<vars.length;i++){
       //iterate through each object and check typeof
    }
}
//this wont work with local variables inside a function
EDIT: SOLUTION BELOW (Credit to this thread by Felix, I just adapted it a little Check if object member exists in nested object)
This works:
if (typeof a != 'undefined' && a.b && a.b.c) alert('c exists')
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.
/**
 * 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 < 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)
}
                The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.
Function scope Variables defined inside a function cannot be accessed from anywhere outside the function, because the variable is defined only in the scope of the function. However, a function can access all variables and functions defined inside the scope in which it is defined.
Try this:
if (a && a.b && a.b.c)
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With