Skip to content

Instantly share code, notes, and snippets.

@sym3tri
Created August 18, 2011 03:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sym3tri/1153228 to your computer and use it in GitHub Desktop.
Save sym3tri/1153228 to your computer and use it in GitHub Desktop.
Safe deep property access in JavaScript
// 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