Last active
June 27, 2016 15:18
-
-
Save gr0uch/e01c035c4b2ec3f2da1e74e37530ff35 to your computer and use it in GitHub Desktop.
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
/** | |
* Given an object and an array of keys, walk over the keys on the object. | |
* | |
* For example: | |
* ```js | |
* walk({ a: { b: [ 0, { c: 2 } ] } }, [ 'a', 'b', 1, 'c' ]) // returns 2 | |
* ``` | |
* | |
* @param {Object} obj | |
* @param {String|Number[]} path | |
* @return {*} | |
*/ | |
function walk (obj, path) { | |
var result = obj | |
var i, j, key | |
for (i = 0, j = path.length; i < j; i++) { | |
key = path[i] | |
if (typeof result === 'object' && result !== null && key in result) | |
result = result[key] | |
else { | |
result = void 0 | |
break | |
} | |
} | |
return result | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment