Iterate Through the Keys of an Object with a for...in Statement. Count is zero

Tell us what’s happening:

I am getting count as zero. I think it is not going into the if statement, and I dont know why. Please help me on this. Thanks

Your code so far
This is 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
  var count = 0;
  for (let usernames in obj) {
    if (usernames.online == true) {
      count++;
    }
  }
  return count;
  // change code above this line
}

console.log(countOnline(users));

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-data-structures/-iterate-through-the-keys-of-an-object-with-a-for---in-statement/

function countOnline(obj) {
let count = 0;
for(let user in obj) {
if(obj[user].online == true) {
count++;
}
}
return count
}

let me explain what it is.

whenever we use for “for in” it return a string of keys , so in your solution you are trying to get property called “online” of a key (usernames=> this is a string of keys of iterated object).
so, we need to find value of those keys. that is why you need to perform like " obj[username].online "

Hope it helps.
thank you

4 Likes

Thanks @Meet . That did it.