Created
April 22, 2017 23:20
-
-
Save jhurliman/431b38d9ee9e2043894d0a2641c547a7 to your computer and use it in GitHub Desktop.
Safely retrieve a value from a nested object with a path like 'a.b.c'
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
/** | |
* Safely retrieve a value from a nested object using a string path such as | |
* 'a.b.c' or an array ['a', 'b', 'c']. | |
*/ | |
function valueAtPath (obj, path) { | |
if (!Array.isArray(path)) { | |
if (!path) return obj | |
path = path.split('.') | |
} | |
if (!path.length) | |
return obj | |
else if (path.length === 1) | |
return obj ? obj[path[0]] : undefined | |
else | |
return valueAtPath(obj[path[0]], path.slice(1)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment