DEV Community

Naveen Dinushka
Naveen Dinushka

Posted on

Iterate through keys of an object using for..in statement (freecodecamp notes)

In a JSON object we have key and value pairs.

An example would be something like this

var object = {
    key1 : {
        name : 'xxxxxx',
        value : '100.0'
    },
    key2 : {
        name : 'yyyyyyy',
        value : '200.0'
    },
    key3 : {
        name : 'zzzzzz',
        value : '500.0'
    },
Enter fullscreen mode Exit fullscreen mode

Exercise

We have defined a function named 'countOnline(userObj)' , using a for ..in statement within this function loop through the users object passed into the function and return the number of users whose online property is set to 'True' . Example of users object that will be passed to countOnline is shown below

{
  Alan:{
     online:false
   },
  Jeff:{
     online:true
},
   Sarah:{
   online:false
}
}
Enter fullscreen mode Exit fullscreen mode

Attempts


//Attempt 1
function countOnline(userObj){
let count;

  for (let user in users) {
       if (user.online==true)
          count ++

    }

}

//Attempt 2
function countOnline(usersObj) {
  // Only change code below this line
  let count=0;
  for (let user in usersObj){

     if(usersObj[user].online==true){
       count++

     }

  }
  return count

  // Only change code above this line
}

console.log(countOnline(users));

Enter fullscreen mode Exit fullscreen mode

Correct answer?? Attempt 2

1.Attempt 1 did not work because when we do user.online, user will only have the string (ie.Alan, Sarah etc)

2.Attempt 2 worked because we correctly used the syntax to get the online property of each user inside usersObj

Try this out in freecodecamp https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-data-structures/iterate-through-the-keys-of-an-object-with-a-for---in-statement

Top comments (0)