1

In ruby, there is a beautiful method that is called .try that allows to access object attributes/methods without risking to get an error.

Eg.

{hello: 'world'}.try(:[], :hello) # 'world'
nil.try(:[], :hello) # nil (no error)

Is there a way to achieve this syntax in ES6 elegantly?

For now, I keep writing the ugly:

if (object && object.key && object.key.subkey) {
  return object.key.subkey
}

Thanks

Augustin Riedinger
  • 20,909
  • 29
  • 133
  • 206

2 Answers2

3

I use lodash _.get:

https://lodash.com/docs/4.17.5#get

e.g.

_.get(object, 'property', null);

Very handy.. if the object doesn't exist it falls back to default passed, e.g. null.

It's really good with deeply nested objects.

e.g.

_.get(object, 'a.b.c.d', 'default');

And some examples from the lodash docs:

var object = { 'a': [{ 'b': { 'c': 3 } }] };

_.get(object, 'a[0].b.c');
// => 3

_.get(object, ['a', '0', 'b', 'c']);
// => 3

_.get(object, 'a.b.c', 'default');
// => 'default'
Terry Lennox
  • 29,471
  • 5
  • 28
  • 40
  • 1
    Yes! There should be a native implementation of this one. Also, I'm not a big fan of a string path description (`a.b.c.d`). Would be nicer to have another operand like `object~key~subkey` for instance. – Augustin Riedinger Mar 26 '18 at 12:46
  • 1
    Yeah, I think this one is great, and should be implemented natively. I've found myself using less and less lodash since ES6, given we now have all the good stuff like map filter reduce etc natively. But the _.get and _.has functions are so useful when traversing object trees. – Terry Lennox Mar 26 '18 at 13:02
1

Try does exist in ES6, it's a little different though. It requires a catch, though, we can leave the catch doing nothing, this is not advised.

const obj = {hello: 'world'};

//passes so does the console log
try{console.log(obj.hello)} catch(e){}
//fails so does nothing
try{console.log(nil.hello)} catch(e){}
Andrew Bone
  • 7,092
  • 2
  • 18
  • 33