Cannot read property '0' of undefined

My Json

[ { user:
     { id: '586214600412758040',
       username: 'Sudhan Playz',
       discriminator: '5859',
       avatar: '65f206f3524c20941c4bca4dffa79c3e',
       short_description: 'Developer of Alexa | Visit: https://alexa-discord.tk/' },
    timestamp: 1585135224508 },
  { user:
     { id: '634701839983706112',
       username: 'khalby786',
       discriminator: '1531',
       avatar: '9a67d6b0212c11fe1aefd3c8b41bb07f',
       short_description: '' },
    timestamp: 1585138569038 },
  { user:
     { id: '592792499739820230',
       username: 'Unique/Dev',
       discriminator: '0005',
       avatar: 'a_3480e96bc7835250a6b47a013172703b',
       short_description: '' },
    timestamp: 1585196167785 }
]

My Main File

json = await res.json();
    let id = message.author.id
    var a = '0'//i tried 0 instead of '0'
    for(a; json.user[a].id = id; a++) {
      var vote;
      vote++;
    }
message.channel.send(vote)

Error: TypeError: Cannot read property ‘0’ of undefined

If you’re planning to do a++, I suggest you declare a as 0 and not a string.

Try json[a].user.id. Because “json” is an array.

It also says the same error

@EnchantedDirt

for(a; json[a].user.id = id; a++) {
}

Error: TypeError: Cannot read property ‘user’ of undefined

For iterating over objects, for…of method is suitable.

for(let user of json) {
if(user.id === message.author.id) {
// Do you stuff

}
}
1 Like

You need to use user.user.id in this case because user contains the whole object, and it has the attribute “user” in it:

for(let user of json) {
   if(user.user.id === message.author.id) {
       // Do you stuff

   }
}