Skip to content

Instantly share code, notes, and snippets.

@AbraaoAlves
Created September 13, 2016 04:16
Show Gist options
  • Save AbraaoAlves/08efc6bac199d0a8e671af1f3ae4a11d to your computer and use it in GitHub Desktop.
Save AbraaoAlves/08efc6bac199d0a8e671af1f3ae4a11d to your computer and use it in GitHub Desktop.
Ruby try function in Javascript today
Object.prototype.tryGet = function(props){
return (props || '').split('.').reduce( (a, b, i, l) =>
(a[b] || (i+1 === l.length ? '': {})
, this)
}
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