Iterate Through the Keys of an Object with a for...in Statement? Help!

Tell us what’s happening:
I can not figure out what is wrong “for the love of all that is holy”! It is driving me crazy! Can someone please tell me what is wrong with my code? Thank you so much!

Your code so far


function countOnline(usersObj) {
// Only change code below this line
let result = 0;
for (let user in obj) {
if (obj[user].online === true) {
  result++;
}
}
return result;
// Only change code above this line
}

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.13; rv:74.0) Gecko/20100101 Firefox/74.0.

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

Link to the challenge:

Do you mean to use obj or userObj.

Also, I think that you are misunderstanding how you are looping. You are grabbing individual users from the array, so usersObj[user] doesn’t really make sense.

I think userObj. Is that what i did wrong?

As I could not find out what I was doing wrong, I took the answer supplied in hint and that is what’s shown above!

That’s the first little thing. With that and one more change I think you’ll be set.

user is an object so you can directly see if it has the online property set to true.

Woops, wrong challenge. You are close. Let me reread.

I think I do not understand this lesson very well.

Ok, here we go:

The syntax

for (let user in usersObj) {
  console.log(user);
}

Is how you retrieve all of the keys in an object. You need the keys to access the components of the object.

In our case, the keys correspond to users. Perhaps an clearer way to say this is

for (let userName in usersObj) {
  console.log(userName);

You need to use the userName to get the user out of the usersObj and check that user for the online property. Since userName is a variable, you’ll have to use [] notation to access the users.

1 Like

Thank you! Thank you! Thank you! i was so stressed! The problem is now solved!

for (let user in usersObj) that’s what I put now and it worked!

1 Like