Created
August 18, 2011 03:27
-
-
Save sym3tri/1153228 to your computer and use it in GitHub Desktop.
Safe deep property access in JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Gets the deep value of property specified in the ns param. | |
// Will always return undefined any properties don't exist or if obj input is invalid. | |
// obj (object): The object to inspect. | |
// ns (array of strings): Ordered properties that are the namespace to the property of interest. | |
// returns: Whatever value the property contains, or undefined | |
function sprop(obj, ns) { | |
var result, i, len; | |
if (!obj) { | |
return; | |
} | |
result = obj; | |
i = 0; | |
len = props.length; | |
for(; i<len; i++) { | |
if (typeof(result) === 'object' && props[i] in result) { | |
result = result[props[i]]; | |
} | |
else { | |
return; | |
} | |
} | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment