[What should I pass in the for loop for the keys? 'obj?'] Iterate Through the Keys of an Object with a for...in Statement

Tell us what’s happening:

Your 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 n=0;
  for(obj in users){
    if(users.obj===true){
      ++n;
    }
  }
  return n;
  // change code above this line
}

console.log(countOnline(users));

obj is the function parameter, if you check the function call at the bottom you will see that the users Object is passed in so you don’t need to reference t inside the function - you should just use the function parameter

Using a for…in loop you do
for (let a in b)
In which a is the property key (the variable of the loop), and b is the object (which you need to specify)

In your case you want to iterate over obj, and for the variable you can use any name you want

Then you need to access the property online of the object inside the object…

Remember to use bracket notation when you use variables to access object properties

1 Like

thanks a lot it was very helpful

I must be missing something between the above discussion and the implementation in my code, because I don’t see what I’m doing wrong.

let count=0;
for (let user in users){
if (obj[user][‘online’]===true){
count ++;
}
}

Nevermind. I just found out my problem and it was as basic as putting my return statement in the wrong place. facepalm