Created
December 24, 2014 16:05
-
-
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".
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
/** | |
* 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