-iterate-through-the-keys-of-an-object-with-a-forin-statement

-iterate-through-the-keys-of-an-object-with-a-forin-statement
0.0 0

#1

Tell us what’s happening:
I’m trying to have a count variable keep track of how many of the users are on line. I suspect my bug is in my if (user.online) call, but I’ve tried every variation I can think of (using users.user.online, online, using brackets around the terms, and can’t get the code to see the online key.

What am I missing here?

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
  let count = 0;
  for (let user in users) {
    if (user.online) {
      count++;
    }
  }
  return count;
  // 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/66.0.3359.139 Safari/537.36.

Link to the challenge:


#2

Let’s first check the type of your user variable in the for-loop:

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

If you run this function, you will find that your user variable has a type of string. So, if you use a for in loop to iterate over an object, you will get the property names back as strings. This is not what you want, because you need the actual object. Given that online is not a property of string, the if statement always results in undefined.

Your users.user.online idea is actually pretty close to the solution. The only problem is that you can’t use dot notation with variables.

Let’s suppose you have an object and the name of a property stored in a variable:

let alan = {
 age: 27,
 online: false
};

let myProperty = 'online';

If you’re trying to access the online property with alan.myProperty, it won’t work. This is because there is no property in the Alan object with the name myProperty. Somehow, the value of the variable needs to be used, instead of the name of the variable. This can be achieved with bracket notation: alan[myProperty].

So, back to your problem: you can get the actual user object by using bracket notation: users[user]. This will give you back an object instead of a string. Then, you can use dot notation to access the online key:

if (users[user].online) {
      count++;
    }

#3

I thought I’d tried that combo. That’s what happens when you code while overtired.

Thank you @thomkhakai !