如何在循环中获取对象'for in'?



fetch('https://api.covid19india.org/state_district_wise.json')
.then(Response => Response.json())
.then(data => {
for(const prop in data){
console.log(prop)
console.log(prop.statecode)  // undefined Why?, How can I access this?
}
})

需要帮助,prop.statecode显示未定义为什么?,我如何访问此?

prop在这里是一个字符串。

您想要的是使用prop作为数据中的密钥来获取对象并从中访问statecode

fetch('https://api.covid19india.org/state_district_wise.json')
.then(Response => Response.json())
.then(data => {
for(const prop in data){
console.log(prop)
console.log(data[prop].statecode)  // undefined Why?, How can I access this?
}
})

您应该使用Object.entries将其转换为键值对,并使用for..of迭代结果。

fetch("https://api.covid19india.org/state_district_wise.json")
.then((Response) => Response.json())
.then((data) => {
//console.log(data)
for (const [key, value] of Object.entries(data)) {
console.log(value.statecode)
}
})

使用对象条目并以keyvalue清晰的方式销毁对象。

fetch('https://api.covid19india.org/state_district_wise.json')
.then(Response => Response.json())
.then(data => {
Object.entries(data).forEach(([key, value]) => {
console.log(value.statecode)
})
})

最新更新