如何快速获取嵌套对象中的值?对象不确定

时间:2017-04-14 08:01:55

标签: javascript

我从后端获取数据,数据是JSON格式并嵌套,如

[{
  a: {
    b: {
      c: 'value',
      ...
    },
    ...
  }
},....]

或者

[{
  a: {
    b: {
      // no  key 'c'
      ...
    },
    ...
  }
},....]

也可能是

[{
  a: {
    // no key 'b'
    ...
  }
},....]

我必须安全地获得'a.b.c',有什么好办法吗?

'A.B.C.D'?

1 个答案:

答案 0 :(得分:0)

您可以像这样使用hasOwnProperty()

if(a.hasOwnProperty('b')){
   console.log(a.b);
}

在此处阅读:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty