Skip to content

Instantly share code, notes, and snippets.

@zgiber
Created October 4, 2020 13:12
Show Gist options
  • Save zgiber/528dd4edf0f03f263ef78a7f7495c130 to your computer and use it in GitHub Desktop.
Save zgiber/528dd4edf0f03f263ef78a7f7495c130 to your computer and use it in GitHub Desktop.
Find nested JavaScript objects by a string path
function deepValue(obj, path) {
// allow path to be passed as a string
if (!Array.isArray(path)){
path = path.split(".")
}
var segment = path[0]
path = path.slice(1, path.length);
obj = obj[segment]
if (!obj) { throw "object not found"}
if (path.length == 0) { return obj }
return deepValue(obj, path)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment