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?
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?
Share Improve this question asked Apr 4, 2018 at 15:55 Örom LoidlÖrom Loidl 3962 silver badges14 bronze badges 1-
5
try
if(apple.details && apple.details.price)
– Sphinx Commented Apr 4, 2018 at 15:55
4 Answers
Reset to default 4Since 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 patible with ES2020 i.e. Most browsers today & node>14.5
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')) { ... }
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)
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.