-1

I have this simple set of data in an array like so:

const mockData = 
{ "data" :
  [
    {
      "id": "76",
      "name": "Dude",
      "time": "08:30"
    },
    {
      "id": "77",
      "name": "Hello",
      "time": "08:40"
    },
  ]
}

I wanted to access each object using for loop, but returned with undefined instead. When I access directly like mockData.data[0].name, I'll get the correct data. But when I use the for loop, I'll be returned with undefined is not an object(evaluating mockData.data[i].name and breaks my app. I'm not sure exactly what's happening, if anyone cares to explain would be nice. Here's my for loop (pretty straight forward).

for(let i = 0; i<=mockData.data.length; i++) {
    if(mockData.data[i].name == "Dude") { //this is the part where the object is undefined
          ... do something
    }
}
Vega
  • 27,856
  • 27
  • 95
  • 103
Falady
  • 124
  • 1
  • 15

1 Answers1

1

Your condition inside for loop is wrong. It should be like i < mockData.data.length

for(let i = 0; i < mockData.data.length; i++) {}

const mockData = 
{ "data" :
  [
    {
      "id": "76",
      "name": "Dude",
      "time": "08:30"
    },
    {
      "id": "77",
      "name": "Hello",
      "time": "08:40"
    },
  ]
}

for(let i = 0; i< mockData.data.length; i++) {
    if(mockData.data[i].name == "Dude") {
      console.log('hi')
    }
}
Sifat Haque
  • 5,357
  • 1
  • 16
  • 23