- Sometimes you may need to iterate through all the keys within an object. This requires a specific syntax in JavaScript called a for...in statement. For our
users
object, this could look like:
for (let user in users) {
console.log(user);
}
- This would log Alan, Jeff, Sarah, and Ryan - each value on its own line.
In this statement, we defined a variable user, and as you can see, this variable was reset during each iteration to each of the object's keys as the statement looped through the object, resulting in each user's name being printed to the console.
Ex: We've defined a function
countOnline
which accepts one argument (a user object). Use a for...in statement within this function to loop through the users object passed into the function and return the number ofusers
whose online property is set totrue
. An example of a users object which could be passed to countOnline is shown below. Each user will have anonline
property with either atrue
orfalse
value.Note: dot-notation will cause errors in this challenge.
[square-bracket] notation must be used to call a variable property name.
{
Alan: {
online: false
},
Jeff: {
online: true
},
Sarah: {
online: false
}
}
function countOnline(usersObj) {
// Only change code below this line
// Only change code above this line
}
- Answer:
let testUser = {
Alan: {
online: false
},
Jeff: {
online: true
},
Sarah: {
online: false
}
};
function countOnline(usersObj) {
let onlineUsers = 0;
for (let user in usersObj) {
console.log(user); // console will display Alan, Jeff, Sarah
console.log(usersObj[user]); // console will display { online: false } { online: true } { online: false }
if (usersObj[user].online === true) {
onlineUsers++
}
}
return onlineUsers;
};
console.log(countOnline(testUser)); // console will display 1
Top comments (1)
is it actually this hard?