Iterate Through the Keys of an Object with a for...in Statement - All most there

Tell us what’s happening:

Hi guys

Any ideas on why this is not going through?

Many thanks,

Danny

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 users in obj) {
  if (obj[users]["online"] == true) {
    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) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 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

you are returning **count variable ** inside for in ,wich means that you are stopping the loop
because the function when it returns something its job stops .
so here in your code you are looping through the first key in the obj (the given object) ,and however the result is , after the if statment it will return 0 or 1 and the function stops
and also change users to another name to not mislead yourself with the name of the object wiich is also users use whaterver name you want instead

Hi I’m on the same topic. I have problem too.

Here is my code. I don’t understand why console.log doesn’t return 27
console.log(user.age); // why don’t return 27

function countOnline(obj) {

let count = 0;
for (let student in obj) {
console.log(student); // Alan
console.log(student.age); // why don’t return 27
if (obj.student.online == true) {
count ++;
}
}
return count;
}

you have to use dot.notation to access the object properties
obj[student].age

1 Like

Thank you very much Mustaphason for your help, it works now !!

1 Like

Hi

Tried to take on what you said, this is where I’m at. Any closer or further away?

function countOnline(obj) {
// change code below this line

let count = 0;
for (let onLine in obj) {
if (obj.onLine.online == true) {
count ++;
}

}
return count;

// change code above this line
}

one of the benefits of using bracket notation is we can use variable inside the brakcet notation to access an objetc property
so here online is a variable
so you can access online property like this
ob[online].online because online is a variable it should be inside bracket notation

let count = 0;
for (let a in obj) {
if (obj[a].online == true) { // so I changed online var by a var  beause we have  already online property 
count++;
}

}
return count;