Skip to content

Instantly share code, notes, and snippets.

@jhurliman
Created April 22, 2017 23:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jhurliman/431b38d9ee9e2043894d0a2641c547a7 to your computer and use it in GitHub Desktop.
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'
/**
* 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