Iterate Through the Keys of an Object with a for in Statement

Tell us what’s happening:
I cant seem to figure out why my onlineUsers variable will not increment, using console.log it returns all the names of the users, but i cant seem to access their online property. Id appreciate any help please, Thank you.

My code so far


let users = {
  Alan: {
    age: 27,
    online: false
  },
  Jeff: {
    age: 32,
    online: true
  },
  Sarah: {
    age: 48,
    online: false
  },
  Ryan: {
    age: 19,
    online: true
  }
};

function countOnline(obj) {
  // change code below this line
  let onlineUsers = 0;
    for (let user in users){
       console.log(user);
         if(user.online === true){
           onlineUsers++;
          
         };
    
    };
   return onlineUsers;  
  // change code above this line
}

console.log(countOnline(users));

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36.

Have you read the MDN docs for the for…in statement?

Look at the example, see if you can first log each nested object.

Also you will want to use the obj parameter instead of the users object directly.

1 Like

Thanks for the quick reply. I’m sorry but I read it and tried to emulate it, but I cant seem to get past the layer of their names, using another for…in seems to only return 0,1,2,3 four times. Also trying to call on the online property seems to always state that “online” has not been defined yet. I feel like im missing something obvious but everything I’m looking up doesn’t seem to work.

Thanks,

  • J

Nevermind I got it. I was determined to make dot notation work but it looks like I needed bracket notation with quotes around “online” to properly bring it up. Well, back to rereading this section before i move on lol. Thanks again.

I remember really wanting the dot to work too at some point. Glad you got it.