Skip to content

Instantly share code, notes, and snippets.

@pyrtsa
Last active January 2, 2016 07:38
Show Gist options
  • Save pyrtsa/8270927 to your computer and use it in GitHub Desktop.
Save pyrtsa/8270927 to your computer and use it in GitHub Desktop.
Yet another get(x, path) and getIn(x, ks) in JavaScript
get([10, 20, {a: 30, b: 'foobar'}], '') //=> [10, 20, {a: 30, b: 'foobar'}]
get([10, 20, {a: 30, b: 'foobar'}], '.2') //=> {a: 30, b: 'foobar'}
get([10, 20, {a: 30, b: 'foobar'}], '.2.b') //=> 'foobar'
get([10, 20, {a: 30, b: 'foobar'}], '.2.b.3') //=> 'b'
function getIn(x, ks) {
for (var i = 0, n = ks.length; x != null && i < n; i++) x = x[ks[i]];
return x;
}
function get(x, path) {
if (path == '') return x;
if (path[0] != '.') return;
return getIn(x, path.slice(1).split(/\./i));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment