Skip to content

Instantly share code, notes, and snippets.

@wmbenedetto
Last active December 14, 2015 11:28
Show Gist options
  • Save wmbenedetto/5078940 to your computer and use it in GitHub Desktop.
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.
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