Reputation: 33
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
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
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