I’ve been trying to get pass this topic, but i can’t get it right. I can’t Seem to figure out What wrong with my code, The For in loops through each Name, then my if statement checks if its online and ill add 1 to my count. and return that count
I would put a link to the topic but it wont let me Basic Data Structures: Iterate Through the Keys of an Object with a for…in Statement
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
}
};
console.log(users[1].online);
function countOnline(obj) {
// change code below this line
var count = 0;
for(let user in users){
if(obj[user].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/71.0.3578.98 Safari/537.36.
For in loop through each enumerable properties of an object.
So to make it simple:
when you write a for loop you increase an index and access the element of an iterable through that index.
With a for in you are iterating over each property.
First of all I there’s an error here console.log(users[1].online);, notice that you don’t have an array of objects, instead you have an object with some nested objects in it as properties. Try logging this console.log(users[0]), this should output undefined because that’s not how you access object properties, but if you log the following console.log(users.Alan) you should get this {age: 27, online: false} which I suspect is the result you’d expect.