[英]how to output keys in a key value pair within nested arrays using constructor Javascript
Within the array of 'items' I wanted to output within the 'info' array only the keys: [ 'stringTwo', 'StringThree' ]
and also output the value String Three
在“项目”数组中,我想在“信息”数组中仅输出键:
[ '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', } ];
I tried with both of these codes: 我尝试了这两个代码:
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)); } })
the first one should output the Keys [ 'stringTwo', 'StringThree' ]
and the second one should output String Three
第一个应该输出Keys
[ 'stringTwo', 'StringThree' ]
,第二个应该输出String Three
I'm wondering why in a more larger scale array that has more key-value pairs both doesn't work and gives me an input of TypeError: Cannot read property 'constructor' of undefined
? 我想知道为什么在具有更多键值对的更大比例数组中既不起作用,又给我输入
TypeError: Cannot read property 'constructor' of undefined
吗? if so are there other ways without using constructor? 如果是这样,还有其他方法不使用构造函数吗?
Your larger scale array probably don't have any info
key. 您的大型阵列可能没有任何
info
键。 To prevent having an error, you should : 为避免出现错误,您应该:
Change your items array to put an info
key, even empty 更改项目数组以放置
info
键,即使是空的
or 要么
Add a typeof data.info !== "undefined"
condition to check if the info
key is defined on each item before trying to access it. 添加
typeof data.info !== "undefined"
条件,以在尝试访问每个项目之前检查是否在每个项目上定义了info
键。
Here is a working example : 这是一个工作示例:
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); } })
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.