How to check if a variable is set inside an object inside another object (js)?

I would like to do this:

if(abc) alert('c exists') //produces error if(a && ab && abc ) alert('c exists') //also produces ReferenceError 

The only way I know this (EDIT: This is apparently the only way):

 if(typeof(a) != "undefined" && ab && abc) alert('c exists'); 

or some type of function like this ...

 if(exists('abc')) 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 on this topic from Felix, I adapted it a little Check if a member object exists in a nested object )

It works:

 if (typeof a != 'undefined' && ab && abc) alert('c exists') 

But the best I have found is to include it in a function. I use two different functions: one to get a variable depth in the object, and one to check if its set is 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) } 
+6
javascript
source share
3 answers

How about this:

 function exists(str, namespace) { var arr = str.split('.'), val = namespace || window; for (var i = 0; i < arr.length; i++) { val = val[arr[i]]; if ( typeof val == 'undefined' ) return false; } return true; } 

Live demo: http://jsfiddle.net/Y3KRd/

+3
source share

Try the following:

 if (a && ab && abc) 
+6
source share

How about a double grade score?

 if (!!a && !!ab && !!abc) 
0
source share

All Articles