Last active
January 2, 2016 07:38
-
-
Save pyrtsa/8270927 to your computer and use it in GitHub Desktop.
Yet another get(x, path) and getIn(x, ks) in JavaScript
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
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' |
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 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