Iterate with key of object with for in statement 90

Tell us what’s happening:

i am not getting i did as u instructed

Your code so far


function countOnline(usersObj) {
// Only change code below this line
let result = 0;
for (let user in obj){
if (obj[user].online === true){
  result++;
}
}
return result;

// Only 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/84.0.4147.105 Safari/537.36.

Challenge: Iterate Through the Keys of an Object with a for…in Statement

Link to the challenge:

shrini, what is “obj”

First you might wanna change the obj to usersObj since the hinted solution is a bit different than what challenge is asking.

The hinted solution works because of couple of important points we need to have in mind when coding in JavaScript.

  1. The data structure we are trying to iterate over is a JavaScript Object. It’s not an Array and it’s not a List as you might have seen in other languages. It’s a data structure that holds some data for you and it’s not indexed.

  2. Since it’s not indexed you can’t easily iterate over a user in users!

  3. What you can do instead is to iterate over the ‘keys’ of the object. Each object has a bunch of keys and bunch of values. Keys are the things before colon ( : ). And values are after it.

  4. Based on the above definition the keys for the usersObj are ‘Alan’, ‘Jeff’, ‘Sarah’ and the values would be whatever to the right side of the colon.

  5. We need to get to the values of these keys since the online being false or true is part of this value. But how do we get to those values ?

  6. We do that by iterating over keys:
    we get each key
    we get to the specific value of that key. i.e the whole thing in braces
    from there we get to the online key and see if the value is true.

  7. So by that for example the first iteration of obj[user].online would be obj[‘Alan’].online. which is false on the first test case so we don’t get into if condition and result remains zero.

Hope my explanation was clear enough, let me know if you needed more info and details.

And good luck :call_me_hand:

1 Like