检查是否定义了obj.prop.innerprop.yetAnotherInnerProp

时间:2018-04-03 19:11:36

标签: javascript ecmascript-6

有没有简单的方法来检查是否定义了深层嵌套的对象?例如,我可以做一些像

这样的事情
typeof obj.prop.innerprop.yetAnotherInnerProp === 'undefined'

这样如果任何内部对象未定义,它应该返回true。

在这种情况下,我们确定obj已定义,但不确定是否定义了propinnerpropyetAnotherInnerProp。我的函数需要yetAnotherInnerProp的值,但在运行时,根obj可以具有与上面显示的结构匹配的结构,或者它可以具有与obj.diffprop.diffinner不同的结构。我想检查yetAnotherInnerProp是否存在。

我知道我可以做点什么,

if(obj.hasOwnProperty('prop')
  if(obj.prop.hasOwnProperty('innerprop')
    if(obj.prop.innerprop.hasOwnProperty('yetAnotherInnerProp')
     value = obj.prop.innerprop.yetAnotherInnerProp

但我想知道是否有更简单的方法来实现这一目标。

0 个答案:

没有答案