-1

What is the right way of checking if a nested property exists?

if (openResult.notification) {
      if (openResult.notification.payload) {
        if (openResult.notification.payload.additionalData) {
          if (openResult.notification.payload.additionalData.sensorOpenWarning) {
            // now do sth with openResult.notification.payload.additionalData
          }
        }
      }
    }
Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
  • You could try the `&&` operator. – Sebastian Simon Mar 14 '18 at 14:26
  • 1
    Possibly better duplicate target: [Test for existence of nested JavaScript object key](https://stackoverflow.com/q/2631001/4642212). – Sebastian Simon Mar 14 '18 at 14:28
  • Welcome to StackOverflow. Please read the help section on how to properly ask questions first. This question is likely to be downvoted / closed, since a simple google search reveals a solution to this problem in the first result (see comment above). Please do some research first. – Jankapunkt Mar 14 '18 at 14:29

2 Answers2

0

Use try catch

var obj;

try{
  console.log(obj.one.two.three.four)
}catch(e){
  console.log("obj is undefined")
}
0

You can use this abbreviate form:

const prop2 = ((obj || {}).prop1 || {}).prop2;

Applied to your code would be:

const sensorOpenWarning = ((openResult || {}).notification || {}).payload || {}).additionalData || {}).sensorOpenWarning;
Rafa Romero
  • 2,667
  • 5
  • 25
  • 51