loop on an object

Loop on an Object

Looping over an object is a common task in JavaScript programming. In simple terms, an object is a collection of key-value pairs, and we need to loop over each key-value pair to access its properties. There are multiple ways to loop over an object, and we will discuss some of the most popular ways in this article.

Using a for...in Loop

The for...in loop is the most popular way to loop over an object in JavaScript. It allows us to iterate over the object's keys and access its values. Here's an example:


    const myObj = { name: "Raju", age: 30, city: "New York" };

    for (let key in myObj) {
        console.log(key + ": " + myObj[key]);
    }

The output of this code will be:


    name: Raju
    age: 30
    city: New York

As you can see, we have used the for...in loop to iterate over the keys of myObj and access its values using bracket notation.

Using Object.keys() Method

The Object.keys() method returns an array of the object's keys, and we can use it to loop over the object. Here's an example:


    const myObj = { name: "Raju", age: 30, city: "New York" };
    const keys = Object.keys(myObj);

    for (let i = 0; i < keys.length; i++) {
        const key = keys[i];
        console.log(key + ": " + myObj[key]);
    }

The output of this code will be the same as the previous example.

Using Object.values() Method

The Object.values() method returns an array of the object's values, and we can use it to loop over the object. Here's an example:


    const myObj = { name: "Raju", age: 30, city: "New York" };
    const values = Object.values(myObj);

    for (let i = 0; i < values.length; i++) {
        console.log(values[i]);
    }

The output of this code will be:


    Raju
    30
    New York

Using Object.entries() Method

The Object.entries() method returns an array of the object's key-value pairs, and we can use it to loop over the object. Here's an example:


    const myObj = { name: "Raju", age: 30, city: "New York" };
    const entries = Object.entries(myObj);

    for (let i = 0; i < entries.length; i++) {
        const key = entries[i][0];
        const value = entries[i][1];
        console.log(key + ": " + value);
    }

The output of this code will be the same as the previous examples.

So, these are some of the most popular ways to loop over an object in JavaScript. You can choose any of these methods depending on your requirements and coding style.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe