4.1 KiB
4.1 KiB
id, title, challengeType
| id | title | challengeType |
|---|---|---|
| 587d7b7d367417b2b2512b1d | Iterate Through the Keys of an Object with a for...in Statement | 1 |
Description
users object and the loop iterates through it to display the user's name to the console.
const users = {In this statement, we defined a variable
Alan: {
age: 30
},
Jeff: {
age: 45
},
Sarah: {
age: 18
}
Ryan: {
age: 24
}
};
for (let user in users) {
console.log(user);
}
// logs:
Alan
Jeff
Sarah
Ryan
user, and as you can see, this variable was reset during each iteration to each of the object's keys as the statement looped through the object, resulting in each user's name being printed to the console.
NOTE: Objects do not maintain an ordering to stored keys like arrays do; thus a key's position on an object, or the relative order in which it appears, is irrelevant when referencing or accessing that key.
Instructions
countOnline which accepts one argument (a users object). Use a for...in statement within this function to loop through the users object passed into the function and return the number of users whose online property is set to true. An example of a users object which could be passed to countOnline is shown below. Each user will have an online property with either a true or false value.
{
Alan: {
online: false
},
Jeff: {
online: true
},
Sarah: {
online: false
}
}
Tests
tests:
- text: The function <code>countOnline</code> should use a `for in` statement to iterate through the object keys of the object passed to it.
testString: assert(code.match(/for\s*\(\s*(var|let)\s+[a-zA-Z_$]\w*\s+in\s+[a-zA-Z_$]\w*\s*\)\s*{/));
- text: 'The function <code>countOnline</code> should return <code>1</code> when the object <code>{ Alan: { online: false }, Jeff: { online: true }, Sarah: { online: false } }</code> is passed to it'
testString: assert(countOnline(usersObj1) === 1);
- text: 'The function <code>countOnline</code> should return <code>2</code> when the object <code>{ Alan: { online: true }, Jeff: { online: false }, Sarah: { online: true } }</code> is passed to it'
testString: assert(countOnline(usersObj2) === 2);
- text: 'The function <code>countOnline</code> should return <code>0</code> when the object <code>{ Alan: { online: false }, Jeff: { online: false }, Sarah: { online: false } }</code> is passed to it'
testString: assert(countOnline(usersObj3) === 0);
Challenge Seed
function countOnline(usersObj) {
// change code below this line
// change code above this line
}
After Test
const usersObj1 = {
Alan: {
online: false
},
Jeff: {
online: true
},
Sarah: {
online: false
}
}
const usersObj2 = {
Alan: {
online: true
},
Jeff: {
online: false
},
Sarah: {
online: true
}
}
const usersObj3 = {
Alan: {
online: false
},
Jeff: {
online: false
},
Sarah: {
online: false
}
}
Solution
function countOnline(usersObj) {
let online = 0;
for(let user in usersObj){
if(usersObj[user].online) {
online++;
}
}
return online;
}