最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Check if sub-object exists before using it - Stack Overflow

programmeradmin0浏览0评论

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
Add a ment  | 

4 Answers 4

Reset to default 4

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 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.

发布评论

评论列表(0)

  1. 暂无评论