Paul
Paul

Reputation: 33

Why calling a property of an object doesn't work in the for of loop?

In this code, I'm trying to call the .password property from the object subsequently with all objects within the array. However, if I'm doing this within the "for of" loop, it doesn't work. But out of the "for of" loop, no issues occur and works as expected.

Is there a reason why it doesn't do the magic properly?

 let users = [
  {name: "Paul", login: "cheerfullime", password: "qqwerty11"},
  {name: "Jack", login: "jackdaniels", password: "browser22"},
]

let counter = 0;
  for (let user of users) {
    console.log(user[counter].password);// This one returns an error
    counter ++;
  }

  users[0].password;//But the same thing out of the for of loop works fine

Upvotes: 1

Views: 582

Answers (2)

Bikram Kumar
Bikram Kumar

Reputation: 443

Here, user is an object and you are trying to access its property using array notation. You should use:

  users.forEach (function (user) {
    console.log(user.password);
  }
)

Or, you can also do it as:

  for (let counter=0; counter<users.length;counter++) {
    console.log(users[counter].password); // use 'users' instead of user
  }

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386660

You iterate the elements of the array with for ... of statement and you can use this object for getting the password.

let users = [{ name: "Paul", login: "cheerfullime", password: "qqwerty11" }, { name: "Jack", login: "jackdaniels", password: "browser22" }],
    counter = 0;
    
for (let user of users) {
    console.log(user.password);
    counter++;
}

Upvotes: 2

Related Questions