Basic Data Structures: Iterate Through the Keys of an Object with a for...in Statement. Is there any way to access user without obj?

Hi all,

I already know the solution of this challenge " Basic Data Structures: Iterate Through the Keys of an Object with a for…in Statement"

as below:
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 onlineCount = 0;
for(let user in obj){
if(obj[user][‘online’]){
onlineCount++;
}
}
return onlineCount;
// change code above this line
}

But I wondered to know is there any way to accessing user without using obj?

1 Like

obj is how is called the parameter you pass inside the function, function countOnline(obj) {...}, and then it is called with countOnline(users)

In this way you can call the function on any object that has a key online, if you access directly the users object your function can’t be reused

Was this you were asking?

user just represents the current key, so it will be "Alan", "Jeff", "Sarah" or "Ryan", it isn’t a thing that exists outside that loop.

Thanks for reply,

Let me clear my question:
If I change the loop as below:

for(let user in obj){
if(user[‘online’]){
onlineCount++;
}
}

the function doesn’t work truly. It seems we can’t access user(inside for loop) in that way and I wonder to know is there any way to accessing user without using obj(inside for loop)?

when user is Alan that would give you Alan["online"], which doesn’t let you call anything, because Alan is a key of an object, so you need to use it to call datas from inside an object, on its own doesn’t do anything

In your case, obj is users becuase you have passed users as argument of the function, and so obj[user]["online"] is equivalent to users["Alan"]["online"].

it is a question of how to call datas from inside an object.

3 Likes

Thanks a lot.

I got it.

1 Like