Skip to content

Instantly share code, notes, and snippets.

@ewebdev
Created December 24, 2014 16:05
Show Gist options
  • Save ewebdev/ffc032bdd738eb5a3e37 to your computer and use it in GitHub Desktop.
Save ewebdev/ffc032bdd738eb5a3e37 to your computer and use it in GitHub Desktop.
Returns the value in within a requested path in a nested object (tree traversal), without using "eval" / "new Function".
/**
* assumption: path contains only key names and dots (.), doesn't handle function calls or array indices
*/
function getVal (obj, path) {
if (path) {
var s = path.split('.'),
cur = s.shift();
if (obj.hasOwnProperty(cur)) {
return getVal(obj[cur], s.join('.'));
}
} else if (!path) {
return obj;
}
throw "item not found";
};
// example:
// getVal({a: {b: 2, c: {t: 10}}}, 'a.c.t')
// > 10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment