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)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

AWS GenAI LIVE!

GenAI LIVE! is a dynamic live-streamed show exploring how AWS and our partners are helping organizations unlock real value with generative AI.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️