Skip to content

Instantly share code, notes, and snippets.

@gr0uch
Last active June 27, 2016 15:18
Show Gist options
  • Save gr0uch/e01c035c4b2ec3f2da1e74e37530ff35 to your computer and use it in GitHub Desktop.
Save gr0uch/e01c035c4b2ec3f2da1e74e37530ff35 to your computer and use it in GitHub Desktop.
/**
* 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