Skip to content

Instantly share code, notes, and snippets.

@monostere0
Last active October 27, 2016 14:04
Show Gist options
  • Save monostere0/b57e7b6b14764e2dca17 to your computer and use it in GitHub Desktop.
Save monostere0/b57e7b6b14764e2dca17 to your computer and use it in GitHub Desktop.
Get object path
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