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
  • 56,346
  • 6
  • 64
  • 75
Vimal kumar
  • 29
  • 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
  • 16,643
  • 2
  • 22
  • 46
Zer0
  • 367
  • 1
  • 4
  • 15
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
  • 16,643
  • 2
  • 22
  • 46
hgb123
  • 11,887
  • 3
  • 15
  • 33
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)

    })
  })
G.aziz
  • 3,365
  • 1
  • 13
  • 30