Created
September 26, 2012 04:17
-
-
Save jgornick/3785996 to your computer and use it in GitHub Desktop.
JavaScript: Walk method (Safe-Navigation)
This file contains hidden or 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
/** | |
* 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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@NeoPhi, fixed! Thanks!