I believe it’s because of the way you have the object key and then another object as it’s property, therefore the online key is buried another level down you would need to know user.Alan.online or something similar.
Sometimes you may need to iterate through all the keys within an object. This requires a specific syntax in JavaScript called a for…in statement.
Your code only works if user is an object.
Try console.log(user) to see what user really is.
function countOnline(obj) {
// change code below this line
let counter = 0;
for (let user in obj) {
console.log(user); // not what you think!
if(user.online === true){
counter ++;
}
}
return counter;
// change code above this line
}
The solution provided by @T-Minus14 is probably a better real world solution but to satisfy this challenge you must use for…in
@cjbechtl your “if” statement has the wrong call to the online property of the users object. see the solution below and notice the if statement
function countOnline(obj) {
// change code below this line
var counter = 0;
for (var user in obj) {
if (obj[user]["online"] === true) {
counter++
}
// change code above this line
} return counter;
}
console.log(countOnline(newUsers));
use bracket notation to access the online property
I’m not an expert but I think your if statement is wrong because it can’t know which object you’re refering to so I think that the problem is not in bracket or dot, it’s that you forgot to include obj as the source.
It has to be: obj[user].online
Exactly. If you are using a variable property name then you must use bracket notation.
const obj = {name:"Sarah",age:23,role:"Zombie Slayer"};
const job = "role";
console.log(obj.role); // this works
console.log(obj["role"]); // this also works
console.log(obj[job]); // this also works
console.log(obj.job); // this does not work
You can access an object’s property either with the dot or bracket notation. The reason the dot notation doesn’t work in this particular case is that if you try to run the code below you will see that the typeof operator returns a string and not an actual object.
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 logged = 0;
for(let user in obj)
{
/*if (obj[user].online)
{
logged++;
} */
console.log(typeof user);
}
return logged;
// change code above this line
}
This should be the top-rated comment. This explains why my solution (as it turns out, the exact same as OP before I came upon this post) didn’t work, and it shows how using variables to access properties needs to look in order to finish the challenge. Thank you so much!