DEV Community

Randy Rivera
Randy Rivera

Posted on • Updated on

Iterating Through the Keys of an Object with a for...in Statement

  • 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);
}
Enter fullscreen mode Exit fullscreen mode
  • 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 of users whose online property is set to true. An example of a users object which could be passed to countOnline is shown below. Each user will have an online property with either a true or false 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
  }
}
Enter fullscreen mode Exit fullscreen mode
function countOnline(usersObj) {
  // Only change code below this line

  // Only change code above this line
}
Enter fullscreen mode Exit fullscreen mode
  • 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
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
hefty006 profile image
HEFTY-006

is it actually this hard?