Örom Loidl
Örom Loidl

Reputation: 386

Check if sub-object exists before using it

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?

Upvotes: 3

Views: 1546

Answers (4)

Ninad P.Chaudhari
Ninad P.Chaudhari

Reputation: 82

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

Upvotes: 4

Ahmad Mageed
Ahmad Mageed

Reputation: 96477

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.

Upvotes: 1

Nurbol Alpysbayev
Nurbol Alpysbayev

Reputation: 21871

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)

Upvotes: 1

ilsotov
ilsotov

Reputation: 162

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

Upvotes: 3

Related Questions