Iterate unknown named object properties

Hi, im working on a function called howMuchOn(users) wich recieves an
object filled with objects as the following example shows:

let users = {
toni: {
age: 33,
online: true
},
emily: {
age: 25,
online: true
},
frank: {
age: 25,
online: false
},
henry: {
age: 24,
online: false
}
};

I need to get out of there just how mucho online:true there are.

Since i actually dont know the names that will come within the main object, i don’t know how to access the property “online” within object “name” within object “users”.

My function simplified looks like this (the question marks ‘???’ is where im stucked) :

function howMuchOn(users) {

var usersOn = 0;

for (var i = 0; i < users.length; i++) {
if ( usuarios.???.online === true){
usersOn += 1;
}
}
return usersOn;
}

I couldnt solve it with for…in loop eather, even tried Object.keys(users) to get an array of the names but couldnt use that array of strings to acces-
Is something like this posible? :

                                                  users[array[0]].online

I insist, its objects within an object, not an array of objects.
getElementsById won’t work, since its no’t an HTML enviroment

Thanks!

Hello @AdrianDante, welcome to the GitHub Support Community!

When looping over objects with unknown properties, you’ll want to use the for … in loop. For example, the following snippet will log the online state of each user to the console.

for (var i in users) {
  console.log(i, users[i].online);
}

Use users[i].online in a condition to determine if you should increment usersOn or not. For example…

var online = 0;

for (var i in users) {
  if (users[i].online) {
    online++;
  }
}

console.log(online); // 2

I think you should be able to accomplish the rest yourself, but if you need anymore help let us know.

Wow, i was apparently just using de for…in loop not correctly, this works great.
Thanks!

1 Like

You’re welcome!

Have a good day. :wave: