2

In order to prevent using an object's value that doesn't exist (which would throw an error), I usually do something like this:

if(apple.details){
   // do something with apple.details
}

and it normally works fine. But if it's about a "object's object's value", like apple.details.price, that doesn't work, because if not even .details exists, the if() would throw an error.

What can I do or is there generally a better way to do this?

Örom Loidl
  • 366
  • 2
  • 12

4 Answers4

3

You can do chain:

if (apple && apple.details && apple.details.price) { ... }

But it's not convenient if the chain is long. Instead you can use lodash.get method With lodash:

if (get(apple, 'details.price')) { ... }
ilsotov
  • 162
  • 1
  • 9
2

Since 2020:

The best way to solve this is using the Optional Chaining Operator

if(apple?.details) // Undefined if apple does not exist

Suggestion of lodash is no longer required when using runtime compatible with ES2020 i.e. Most browsers today & node>14.5

1

You may try solution of @Sphinx

I would also suggest _.get(apple, 'details.price') of lodash, but surely it is not worth to include whole library for simple project or few tasks.

_.get() function also prevents from throwing error, when even apple variable is not defined (undefined)

Nurbol Alpysbayev
  • 19,522
  • 3
  • 54
  • 89
1

You would have to check each parent object prior to checking the nested child object, i.e., if (a && a.b && a.b.c) {}

If you're using LoDash, you can use the _.get function with an optional default:

let obj = {'a': {'b': {'c': 42} } };
let result = _.get(obj, 'a.b.c'); // 42
let result2 = _.get(obj, 'a.b.d'); // undefined
let result3 = _.get(obj, 'a.c.d', null); // null

If you're not using LoDash, you can implement a simplified version of _.get as shown in this answer.

Ahmad Mageed
  • 94,561
  • 19
  • 163
  • 174
  • This would provide more value if the final sentence was added as comment on the selected answer. – JonSG Apr 04 '18 at 16:49
  • @JonSG odd perspective. All of the answers here were posted within minutes of each other, as often happens on this site. None were selected as the answer at the time of this post. – Ahmad Mageed Apr 04 '18 at 17:29
  • Don't get your hackles up! There is now an "accepted answer" that is not this one. Your final sentence would be a valuable addition to the "accepted answer". I did not say you copied anyone did I? Frankly I expect more from someone with 72k rep. – JonSG Apr 05 '18 at 15:48