Accessing object elements using for loop

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 ur in obj){
    if(ur.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 6.3; 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

i

To access the property online inside the objects you need to use obj[ur].online

Because, ur is at first “Alan”, so at first you call obj["Alan"].online, and the same for the others

You use bracket notation because that one can use variables inside it, when dot notation can’t (obj.ur.online would search for something called ur inside the object)

1 Like

thanks a lot!! :slight_smile: