Created
September 13, 2016 04:16
-
-
Save AbraaoAlves/08efc6bac199d0a8e671af1f3ae4a11d to your computer and use it in GitHub Desktop.
Ruby try function in Javascript today
This file contains hidden or 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
Object.prototype.tryGet = function(props){ | |
return (props || '').split('.').reduce( (a, b, i, l) => | |
(a[b] || (i+1 === l.length ? '': {}) | |
, this) | |
} |
This file contains hidden or 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
var obj = {a:{b:{c:1, d:2}}}; | |
obj.tryGet('a.b.c');//print 1 | |
obj.tryGet('a.b.d');//print 2 | |
obj.tryGet('a.b.c.a');//print '' | |
obj.tryGet('a.c.b.d');//print '' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment