Last active
January 21, 2019 09:37
-
-
Save dimensi/34e05a32c65d6f70046c7056dd111888 to your computer and use it in GitHub Desktop.
getByPath function get
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
/** | |
* | |
* @param {object} obj | |
* @param {string} path | |
* @example ```js | |
getByPath(obj, 'a.c.b.0.c') | |
``` | |
*/ | |
export const getByPath = (obj, path) => { | |
if (obj == null) return null | |
const arrPath = path.split('.') | |
const length = arrPath.length | |
let index = 0 | |
let result = obj | |
while (index < length) { | |
const key = arrPath[index] | |
index += 1 | |
if (result[key] == null) return null | |
result = result[key] | |
} | |
return result | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment