Languages

JavaScript - check nested object properties for null/undefined

0 points
Asked by:
Aaron1
568

Let's say I have an object:

it gets populated through the course of using the app, for example:

At another place in the code I want to check if myObject.metadata.type exists.

If it doesn't exists, the code will cause an error.

Also if myObject.metadata is undefined, myObject.metadata.type of course is undefined too.

That means I need to check it like this:

I don't think it is efficient way to check this, since the bigger objects are, the worse it gets.

Is there a better way to check conditions like this?

1 answer
0 points
Answered by:
Admin Dirask Community
4380

1. Using optional chaining (ES 2020+)

In dirask snippets you can find some reusable arrow functions:

2. Alternative solution

You can create a custom function:

 

See also

  1. JavaScript - get object property by path

  2. Dirask Snippets - get nested property value by path (resistant to null/undefined)

References

  1. String.prototype.split() - JavaScript | MDN
  2. Array.prototype.reduce() - JavaScript | MDN
  3. Conditional (ternary) operator - JavaScript | MDN
0 commentsAdd comment
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join