Last active
December 14, 2015 11:28
-
-
Save wmbenedetto/5078940 to your computer and use it in GitHub Desktop.
The examples in this gist will let you look up a property in a nested JavaScript object using a dot-delimited object path. A string like `foo.bar.baz` can be used to look up the value of `baz` in an object where baz is nested inside of bar which is nested inside of foo.
This file contains 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
var lookup = function(dotPath,sourceObj){ | |
var parts = dotPath.split('.'); | |
var lastPart = parts.pop(); | |
var len = parts.length; | |
var counter = 1; | |
var current = parts[0]; | |
while ((sourceObj = sourceObj[current]) && counter < len){ | |
current = parts[counter]; | |
counter += 1; | |
} | |
if (sourceObj){ | |
return sourceObj[lastPart]; | |
} | |
}; | |
/*----------- Usage examples -----------*/ | |
var obj = { | |
foo : { | |
bar : { | |
baz : 'SUCCESS!', | |
biz : ['first','second','third'] | |
} | |
} | |
}; | |
lookup('foo.bar.baz',obj); // Outputs "SUCCESS!" | |
/* Also works with nested arrays */ | |
lookup('foo.bar.biz.1',obj); // Outputs "second" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment