Created
October 4, 2020 13:12
-
-
Save zgiber/528dd4edf0f03f263ef78a7f7495c130 to your computer and use it in GitHub Desktop.
Find nested JavaScript objects by a string path
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
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