Can not pass quiz

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

Who can show what is wrong with my code ?

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 key in obj) {
if (key["online"] ) {
  count++;
   console.log(key,count);
} 

};

console.log(users.Ryan.online)
  // change code above this line
}

console.log(countOnline(users));

What question do you think this if statement is posing?

So with this data structure you have objects within an object. When you first loop through users each key is going to be a user’s name. Therefore users[key] is how you access the object associated with each user. users['Ryan'] gets you the the object {‘age’: 19, ‘online’: true}. Now you need to access the ‘online’ attribute of this object on each loop iteration.

Remember, to access an object attribute the syntax is:
object['key']
or
object.key

if (key.online ) {
  count++;
   console.log(key,count);
} 

not working , do not understand …(

You need to use the key (user name) to access the original object:
obj[key]['online']

  • obj refers to the original object acceped in the function.
  • [key] access the user object of each user. On the first run of the loop key === 'Alan', on the second it’s Jeff, then Sarah, etc…
    • Unfortunately, in this circumstance using obj.key literally means obj['key'], trying to access an attribute called ‘key’ in the original object. Which isn’t useful here. When in doubt, go with bracket notation over dot notation to avoid this.
  • ['online'] access the ‘online’ attribute of each user object
1 Like

Have a look at the for…in docs. See if you can figure out how to use the key and obj together. It may help to think of the key like the index inside a normal for loop.

In your for...in loop try logging key, now try logging obj, now again think about how you can combine key and obj.

1 Like
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 = 1 ;
for (let key in obj) {
if (obj[key]['online']) {
  count++;
 
   return count;
} 
console.log(count);
};

console.log(users.Ryan.online)
  // change code above this line
}

console.log(countOnline(users));

The function counts is well but can not pass …

you have the return statement inside the loop , when a return statement is executed, the function is exited and stops

1 Like

Thank you ) I must remember thet return stops tthe function:grin: