Basic Data Structures: Iterate Through the Keys of an Object with a for...in Statement: why doesn´t this code work?

Basic Data Structures: Iterate Through the Keys of an Object with a for...in Statement: why doesn´t this code work?
0

#1
let users = {
  Alan: {
    age: 27,
    online: false
  },
  Jeff: {
    age: 32,
    online: true
  },
  Sarah: {
    age: 48,
    online: false
  },
  Ryan: {
    age: 19,
    online: true
  }
};
console.log(users.Alan["online"])

function countOnline(obj) {
for (let user in obj){
let counter=0;
if(obj.user["online"]===true){
  counter ++
}
 return counter

}
  // change code above this line
}

console.log(countOnline(users));

#2

Hello, read this post Help - Dot Notation vs Bracket Notation -
I think this is what’s going on.


#3

That doesn´t help because user.online is a valid prop (same as user[“online”])


#4

Oh, your return is inside your for loop. Also, you can drop the comparator inside your if.


#5

Nope, that doesn´t work either.


#6

I copied your code and tweaked it a little:

  // change code below this line
  let counter=0;
    for (let user in obj){
     // console.log(users[user]["online"]); Debug line
      if(obj[user]["online"]){ /* If(true) */
        counter ++;
      }
    }
  return counter;

  // change code above this line
}

Dot notation doesn’t work because the user variable given from the for…in loop is a string.
Bracket notation on the other hand requires the use of strings, and a string is exactly what user is! I’m sure you can find further info, as I’m just finding out about these kind of subtleties