Tell us what’s happening:
I can’t find what is wrong in my code. Can someone please help me?
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 count = 0;
for(let user in users){
if(user['online'])
count++;
}
return count;
// change code above this line
}
console.log(countOnline(users));
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:68.0) Gecko/20100101 Firefox/68.0.
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/
ILM
August 22, 2019, 7:14am
2
the for…in loop gives strings that are the object keys
so user is a string and doesn’t have properties like an object
an other thing you may consider is that you are in a function, and best practice is to use the function parameter
function countOnline(obj) {
// change code below this line
let count = 0;
for(let user in obj){
if(user == true)
count++;
}
return count;
// change code above this line
}
I changed my code into this still wrong.
ILM
August 22, 2019, 7:20am
4
try using console.log(user) in your loop to understand what user is
I know it’s the names of the users. But how can I judge the value of online to be true.
ILM
August 22, 2019, 8:04am
6
you have an object
let users = {
Alan: ...
Jeff: ...
Sarah: ...
Ryan: ...
}
the names are the keys of this object, each of this properties has value of an other object
do you remember how to access nested objects?
I’ve been using obj.key to access nested array, but why can’t I be admitted on this one…
function countOnline(obj) {
// change code below this line
let count = 0;
for(let user in obj){
//console.log(user);
if(user.online == true)
count++;
}
return count;
// change code above this line
}
Hmm I don’t see why your first technique isn’t correct either…
I know the answer!!! The answer is to change " user.online" into “obj[user].online” so that we can use the string into the JavaScript syntax.
3 Likes