How To Loop Through An Object in JavaScript

How To Loop Through An Object in JavaScript

A loop in computing is an instruction that iterates or repeats or executes one or more statements over and over again.

Some loops execute the statement so long as the specified condition is true, while others execute the statement up to a number of times.

I'm sure there's a loop functionality in your music player, where you can select a particular song to be repeated over and over again. This means that a loop basically repeats something!

Today, I will talk about how to loop through an Object. But before we continue, I would like you to understand what Objects are and how you could create one.

REFRESHER

What is an Object?

An Object is a special kind of array that stores data as a {key-value} pair. A single pair of this data is called a property of that object.

Below are some of the ways to create an object in JavaScript;

Object Literal

Using the object literal {}, we can create a simple object that stores a user's name and email address.

const profile = {
    name : "Simon",
    email : "me@you.com"
}
//retrieve the user's name
console.log(`${"Hello ", +profile.name}`);

Constructor Function

A constructor function is a function that is used to create an object.

You just have to declare the function, then make use of this keyword within the function to set the function's properties.

function profile(name, email){
    this.name = name;
    this.email = email;
}
//create new instance
const myProfile = new profile("simon", "test@gmail.com");
//retrieve user email
console.log( `${"My email is "+ myProfile.email}` );

You can see how I declared the function, then made use of this keyword to define properties that the function will have.

To create an object using a constructor function, you have to create a new instance of that function using a new keyword.

Factory Function

A factory function is a function that returns an object. To create a factory function, you must first declare a function, then on your return statement, use the Object literal notation to return the object.

function profile(name, email){
    return{
        name : name,
        email : email
    }
};
//invoke function
const myProfile = profile("Tony", "test@gmail.com");
//access property
console.log("My name is "+myProfile.name);

Having refreshed your memory, I will show you different approaches to looping through an Object.

Before we proceed with any of the approaches, I would like you to understand these two Object methods.

  • Object.keys()

This method helps to retrieve all keys belonging to an Object as an Array

  • Object.values()

This method helps to retrieve all values belonging to an Object as an Array

With a knowledge of the object methods above, we can write a loop that will loop through an object.

APPROACH 1 ( Using a number as the Index )

Now, remember that an Object property is just a combination of a key and a value ie { key : value }. So using the Object.keys() method, we can retrieve all keys belonging to an Object, loop through the keys using a while-loop, and then with a particular key as a numeric index, we will retrieve the value that is assigned to it.

const profile = {
    name : "Simon",
    email: "me@you.com",
    gender : "male"
}
let i = 0;
//get the length of the object
while( i < Object.keys(profile).length ){
    //since we hold the current index, retrieve the key and value assigned to it
    console.log( Object.keys(profile)[i]+' = '+Object.values(profile)[i] );
    i++;
}

In the code above, the object has 3 properties and in order to loop through the object's keys, we have to:

  • Query the length of the keys
  • Access all object keys and check the key that is present at the specified index.
  • Access all object values and check the value that is present at the specified index.

image.png

APPROACH 2 ( Using a key as the Index )

Recall that using Object.keys() method retrieves the object's keys as an Array.

In this approach, we will use a for-each loop to loop through the object's keys which are returned as an Array, then with a particular key as the element at hand, we can access the value assigned to it.

const profile = {
    name : "Simon",
    email: "me@you.com",
    gender : "male"
}
//loop through keys
Object.keys(profile).forEach( (key) => {
    //access object value using key
    console.log( key+' = '+profile[key] );
});

loop_through_object_approach_2_code.png

APPROACH 3 ( Using for..in loop )

Considering the second approach above, we can achieve the same results by using the for ...in loop.

In this approach, we need to define the loop's syntax to access each key present in the object. Then with each key accessed, retrieve the associated value.

for (let key in profile) {
    console.log(key +' = '+ profile[key]);
}

This approach is by far the easiest way to loop through an Object.

loop_through_object_approach_2_code.png

I hope you've understood the 3 approaches you could use to loop through an Object in JavaScript.

You've reached the end of my article.

EXTRA

I recently launched a JavaScript package that validates your HTML forms using validation rules, regular expressions, and form input attributes.

I will appreciate it if you spared a few seconds to check it out.

Thank You

Image Credit: Tine Ivanič on Unsplash