0

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

Need Help, prop.statecode show undefined Why?, How can I access this?

Nicholas Tower
  • 72,740
  • 7
  • 86
  • 98
Vimal kumar
  • 39
  • 2
  • 5
  • 3
    `prop` is the key, not the object. You can use `data[prop]` to get the value/object – Nick Parsons Jul 31 '20 at 15:08
  • 2
    ^ Thus `data[prop].statecode` to access the state code of each value. – 3limin4t0r Jul 31 '20 at 15:11
  • Does this answer your question? [For-each over an array in JavaScript](https://stackoverflow.com/questions/9329446/for-each-over-an-array-in-javascript) – VLAZ Jul 31 '20 at 15:16

3 Answers3

2

prop is a string here.

What you want is to use prop as the key in data to get hold of the object and access statecode from it.

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?
     }
  })
3limin4t0r
  • 19,353
  • 2
  • 31
  • 52
Zer0
  • 448
  • 1
  • 5
  • 16
1

You should convert it to key-value pairs with Object.entries and iterate through the result with 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)
    }
  })
3limin4t0r
  • 19,353
  • 2
  • 31
  • 52
hgb123
  • 13,869
  • 3
  • 20
  • 38
0

Use Object entries and the destruct your object in a way that key and value are clear.

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)

    })
  })
Aziz.G
  • 3,599
  • 2
  • 17
  • 35