Stuck on Iterate Through the Keys of an Object with a for...in Statement

Stuck on Iterate Through the Keys of an Object with a for...in Statement
0

#1

**I’m stuck, of course.

I believe that this code should iterate through each property, check to see if it has an online property of true, and, if it does, add 1 to the variable i.

Once it has iterated through the object, it should return i, which should be equal to the number of properties with an online value of true.

Yet, it is not working, and I don’t understand why. **

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 i = 0;
for (let user in obj) {
  
  if (user['online'] === true) {
i += 1;
  }

 
}
return i;
  // 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/68.0.3440.106 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


#2

You seem not to understand what the user variable is in each iteration of the for loop. It turns out that user is just a string with values like “Alan”, “Jeff”, etc. You thought user was an object which is why you tried to access a property named “online” from it. Now that you know user is just a string, try to rewrite your solution.


#3

This isn’t a proper way to access ‘online’ keys in your object.

Hint: obj[user] will return each sub object.


#4

for…in loops through the properties(keys) of the object, and in each iteration/loop it will return one key at a time. in your example keys of users object are Alan, jef … and so on. To get the access of online property/key you should use users[Alan][online]


#6

Thanks everyone.

I’ve gotten past that one and I am moving along again.

Happy coding!