首页 > 解决方案 > 如何在“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 显示 undefined 为什么?,我怎样才能访问它?

标签: javascriptapifetch

解决方案


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?
     }
  })


推荐阅读