What's wrong in this: Iterate Through the Keys of an Object with a for...in Statement

What's wrong in this: Iterate Through the Keys of an Object with a for...in Statement
0

#1

Tell us what’s happening:

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 obj)
  {
if(obj['online']!=true){
    obj['online']=true;
    count=count+1;}
  }
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) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36.

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


#3

Nope, i am accessing in the same way; @fmahaztra


#4

Sorry, that previous answer was wrong. I just took a look at the exercise (I haven’t gotten that far yet haha).

When you do a for-in loop, in this case with:

for(let user in obj)

The “user” here are the properties of the “obj” object, not the values within the “obj” object. In this case, the values of the “obj” object are the data of the individual users, which is what you’re trying to access to look for their online status. So you should try and do something along the lines of:

obj[user]['online']

In accessing the property you want. Hope that’s more helpful.


#5

no, it’s not write. @fmahaztra


#6

There’s another bug in your code which is preventing you from moving to the next exercise. I’m not sure if I’m allowed to give you the entire solution.

Hint: You should only check if they’re online and count up the users that are online, you shouldn’t make the offline users have an online status and count them up.


#7

it’s returning correct ‘2’ but answer is wrong;


#8

What you have here is an object containing 4 objects. So your for...in loop, lists each object inside the main object. user in this case represents one of the objects.

One thing to note though is that you should always verify that the key (user) is actually a property of your object and doesn’t come from the prototype instead. You can do this with hasOwnProperty().

So to correct that part of your code, it should be:

for(let user in obj)
{
	if (obj.hasOwnProperty(user)) {
		if(user['online']!=true){
			user['online']=true;
			count=count+1;
		}
	}
}

I’m not saying that this is enough to solve the challenge. That’s up to you. But this is the correct way to do it (I’ve verified it).


#9

That’s odd. I managed to solve it by checking if

obj[user]['online']

Is true for each user in the “obj” object, counting up the ones that are online, and returning that count.