Skip to content

Instantly share code, notes, and snippets.

@jgornick
Created September 26, 2012 04:17
Show Gist options
  • Save jgornick/3785996 to your computer and use it in GitHub Desktop.
Save jgornick/3785996 to your computer and use it in GitHub Desktop.
JavaScript: Walk method (Safe-Navigation)
/**
* Walks the object by the specified path and returns the value.
*
* @see http://groovy.codehaus.org/Operators#Operators-SafeNavigationOperator
* @see "The Existential Operator" at http://coffeescript.org/#operators
*
* @example
* var foo = { bar: { baz: true }, biz: null };
*
* walk(foo, 'bar.baz'); //-> true
* walk(foo, 'baz.bar'); //-> undefined
* walk(foo, 'biz.bar'); //-> undefined
*
* @param {Object} object
* @param {Array|String} path A dot notated path or an array of paths.
*
* @return {Mixed|undefined} Returns undefined when not found.
*/
function walk(object, path) {
if (typeof path == 'string') {
path = path.split('.');
}
for (var i = 0, len = path.length; i < len; i++) {
if (!object || typeof (object = object[path[i]]) == 'undefined') {
object = undefined;
break;
}
}
return object;
}
@jgornick
Copy link
Author

@NeoPhi, fixed! Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment