I was wondering if there is a neat way of doing this:
if (app && app.object && app.object.foo) {
alert(app.object.foo.bar);
}
This is really long and "ugly".
I found out that Angular2 has something really great for cases like this. But I think it's only for templates:
<div>{{this?.object?.foo?.bar}}</div>
This got me really exited because I have a lot of code that looks just like the first example. It get's the job done but I'm really hopping there is something more sophisticated.
Many languages have this functionality, some call it safe navigation operator
or even Elvis operator
(yes haha).
JavaScript does not have this functionality. If you are open to use CoffeeScript
, you might take a look at the existential operator.
But, if you want to keep with JS, you should take a look at lodash.get()
, which lets you do something like this:
var object = { 'a': [{ 'b': { 'c': 3 } }] };
_.get(object, 'a[0].b.c');
// → 3
_.get(object, 'a.b.d.c', 'default');
// → 'default'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With