How to check if object within object exists

后端 未结 6 768
慢半拍i
慢半拍i 2021-01-12 08:21

It seems that the following technique for checking the existence of an object member produces an error because the \'bar\' parent object hasn\'t been declared before the che

6条回答
  •  天涯浪人
    2021-01-12 08:37

    It can be done simply using the code below:

    var newVal = (foo && foo.bar && typeof foo.bar.myVal !== 'undefined') ? foo.bar.myVal : foo.bar.myVal
    

    A property is null or undefined, it will be evaluated as false so the above code will only process up to the first 'false' statement.

提交回复
热议问题