如何使用构造函数输出嵌套数组中键值对中的键 Javascript

how to output keys in a key value pair within nested arrays using constructor Javascript

在 'items' 数组中,我想在 'info' 数组中仅输出键:[ 'stringTwo', 'StringThree' ] 并输出值 String Three

let items = [
  {
    string: 'string1',
    info:
    {
      stringTwo:'String Two',
      stringThree: 'String Three'
    },
    size:3445
  },
  {
    string: 'string2',
    info: 'ruby files'
  },
  {
    string: 'string3',
    info: ''
  },
  {
    string: 'string4 without info key',
  }
];

我尝试了这两个代码:

data.forEach((data) => {
  if(data.info.constructor === Object) {
    console.log(Object.keys(data.info));
  }
})

data.forEach((data) => {
  if(data.info.constructor === Object) {
    console.log((data.info.stringThree));
  }
})

第一个应该输出密钥[ 'stringTwo', 'StringThree' ] 第二个应该输出 String Three

我想知道为什么在具有更多键值对的更大范围的数组中都不起作用并给我输入 TypeError: Cannot read property 'constructor' of undefined? 如果可以,还有其他不使用构造函数的方法吗?

您的较大比例阵列可能没有任何 info 键。为防止出现错误,您应该:

  • 改变你的项目数组来放置一个info键,甚至是空的

  • 添加一个typeof data.info !== "undefined"条件来检查如果info在每个项目上定义,然后再尝试访问它。

这是一个工作示例:

let items = [
  {
    string: 'string1',
    info:
    {
      stringTwo:'String Two',
      stringThree: 'String Three'
    },
    size:3445
  },
  {
    string: 'string2',
    info: 'ruby files'
  },
  {
    string: 'string3',
    info: ''
  },
  {
    string: 'string4 without info key',
  }
];


items.forEach((data) => {
  if(typeof data.info !== "undefined" && data.info.constructor === Object) {
    console.log(data.info.stringThree);
  }
})