I have been working on this (what I expect is relatively simple) challenge for about an hour. I have used the solution below (provided by freeCodeCamp) verbatim to no avail.
function countOnline(obj) {
// change code below this line
let result = 0;
for (let user in obj) {
if (obj[user].online === true) {
result++;
}
}
return result;
// change code above this line
}
console.log(countOnline(users));
I believe there have been some tweaks to the exercise since the initial solution, so I have attempted to tweak the solution to match (ie. object name is different). I have checked and rechecked the syntax over and over again and if it is wrong, it is because it is just out of the reach of my understanding at this point. JS has been challenging for me up to this point, but I really feel like I understand it well enough to get this answer correct, but I just keep missing something. Please help!
function countOnline(usersObj) {
// Only change code below this line
let result = 0;
for (let user in usersObj) {
if (usersObj[user].online === true) {
result++;
}
}
return result;
// Only change code above this line
}
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36.
Challenge: Iterate Through the Keys of an Object with a for…in Statement
Your modification of the solution is correct and passes for me.
There are two key parts.
First,
for (let user in usersObj) {
is important. In this line, you are looping over all of the users in the usersObj.
Next,
if (usersObj[user].online === true) {
is also important. In this line you are using the user values that you are looping over. However, you need the information in the usersObj about this user, or usersObj[user]. Specifically, you need the online status of the user, or usersObj[user].online.
I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.
Please use the “preformatted text” tool in the editor (</>) to add backticks around text.
I finally got it to pass. I am not sure exactly why it did not pass earlier as shown above, but most recently I was able to get it to pass by changing to location of a closing curly bracket. During the many tries, I apparently put the return result inside the for in statement instead of outside. Thanks for the help!