Skip to content

Instantly share code, notes, and snippets.

@dimensi
Last active January 21, 2019 09:37
Show Gist options
  • Save dimensi/34e05a32c65d6f70046c7056dd111888 to your computer and use it in GitHub Desktop.
Save dimensi/34e05a32c65d6f70046c7056dd111888 to your computer and use it in GitHub Desktop.
getByPath function get
/**
*
* @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