如何使用构造函数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);
}
})

最新更新