For...in Statement challenge

I am unable to solve this 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/

Given below is my code but I am unable to pass the challenge. Need help please.

function countOnline(obj) {
// change code below this line
for(let user in obj) {
if(obj[user].online == true) {
console.log(user);
}
}
// change code above this line
}

console.log(countOnline(users));

countOnline function doesnt return anything

What you were supposed to do in the challenge was to return the number of users whose online property is set to true, not to show them on the console. Simple steps you have to follow:

  1. declare a variable inside the function with 0 value;
  2. increment it in the if block
  3. return at the end of the function.

Thanks guys, I did it my way. I initialized an empty array and then pushed all the user into it and then return the length of the array. It did the trick…

like this
let arr = [];
arr.push(user);
return arr.length;

1 Like

tried this

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

but doesn’t work

user is a string, it doesn’t have the online property. what the for…in loop gives you is the keys of the object properties. So, how do you access an object property with variables?

Check my previous answer it works like that.
And try using obj(user).online instead of user.online.