如何检查嵌套属性是否存在?

时间:2018-03-14 14:24:46

标签: javascript

检查嵌套属性是否存在的正确方法是什么?

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

2 个答案:

答案 0 :(得分:0)

使用try catch

var obj;

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

答案 1 :(得分:0)

您可以使用此缩写形式:

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

应用于您的代码将是:

const sensorOpenWarning = ((openResult || {}).notification || {}).payload || {}).additionalData || {}).sensorOpenWarning;