Iterate Through the Keys of an Object with a for...in Statement2

Tell us what’s happening:
I am sincerely tired try out different odes and it just isn’t working.

Can someone help with an explanation please.

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
  for(let avail in obj){
    if(avail.online === true){
      return avail ;
    }
  }
  // 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/74.0.3729.169 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/

According to the instructions (see below), you are supposed to return the number of users whole online property is true.

We’ve defined a function, countOnline ; use a for…in statement within this function to loop through the users in the users object and return the number of users whose online property is set to true .

One way to approach this is to have a variable which keeps track of the number of users with online property of true. The variable’s value would need to start at 0. Then everytime a user (which is an object) has an online property value of true, you would increment the variable’s count.

Unfortunately, your current code iterates through the object properties (which are strings like ‘Alan’, ‘Jeff’, ‘Sarah’, and ‘Ryan’) and you try to reference an online property on these strings. Strings do not have an online property. Your avail represents each of these strings during each iteration. You can think of them as keys of the object. You have already learned how to access an object’s property value using a variable. Keep in mind you have nested objects here, so you will if you do not remember how to work with nested objects, you will need to go back to the Basic JavaScript section and review that challenge and the challenge for how to access an object’s property with a variable.

3 Likes

Thank you. I finally figured it out…Had to go back to my notes on object.

Thanks a lot