Json密钥无法访问键值



我将获得一个动态json作为响应,所以我使用下面的来获得密钥名称,我总是想要第三个键值,它要么是true,要么是false。因此,我使用下面存储在TypeIs中的来获得第三个键的值,当我尝试访问json时,我会得到未定义的

Json 示例

submitResult = [{
ComodityID: 33,
ComodityName: 'LED',
field1: true
}, {
ComodityID: 342,
ComodityName: 'Installing ',
field1: true
}, {
ComodityID: 322,
ComodityName: ' Bracket',
field1: true
}
]

在动态json:中查找第三个密钥名称

var theTypeIs = Object.keys(submitResult[i])[2];
console.log(submitResult[i].theTypeIs)

当我控制台记录它时,我没有定义。有人能帮我吗。提前谢谢。

console.log(submitResult[i].theTypeIs)打印undefined,因为submitResult[i]没有属性theTypeIs

通过变量访问属性时,需要使用括号表示法

console.log(submitResult[i][theTypeIs])

您应该使用括号表示法:

console.log(submitResult[i][theTypeIs]);
enter code 

const submitResult= [{ ComodityID: 33, ComodityName: 'LED', field1: true }, { ComodityID: 342, ComodityName: 'Installing ', field1: true }, { ComodityID: 322, ComodityName: ' Bracket', field1: true }]
//To get the third key which is field1
you can run a loop i to length
const {field1} = submitResult[i];

最新更新