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

0

2 Answers 2

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'
Sign up to request clarification or add additional context in comments.

2 Comments

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.
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.
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){}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.