0

I am having trouble with a javascript for in loop.

How come console.log(user) logs the number "0" when looping over users?

Is it showing the array position of the user object or something?

I want to log each object in the array...

Thank you

router.post( "/api/verification/check", auth, async (req, res) => {
    try {
      const users = await User.find({ /* gets user/s */ })

      console.log(`${users}`)           // logs user object

      for (const user in users) {
        console.log(user)               // logs "0" ???
   
      }

    } catch (err) {
      res.status(400).send()
    }
  }
)

1 Answers1

0

The for-in loop will give you the index of the array, not the value. If you need the value you should look it up using the index.

for (const i in users) {
   console.log(users[i]);
}

[update] You can also use the for-of loop instead.

for (const user of users) {
   console.log(user);
}
Leroy
  • 1,600
  • 13
  • 23