Last active
October 27, 2016 14:04
-
-
Save monostere0/b57e7b6b14764e2dca17 to your computer and use it in GitHub Desktop.
Get object path
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
function get(obj, path) { | |
let spl; | |
return new Function( | |
`return arguments[0]&&${(spl = path.split('.')).reverse().map((prop, index) => { | |
return `arguments[0].${spl.slice(spl.length - index - 1).reverse().join('.')}`; | |
}).join('&&')}`)(obj); | |
} | |
//usage: | |
// const hello = {world:{foo:{bar:baz:1}}} | |
// get(hello, 'world.foo.bar.baz') // returns 1 | |
// const hello2 = {foo:{bar:[1,2,3]}}; | |
// get(hello2, 'foo.bar[1]') // returns 2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment