How to loop through object - JavaScript
Mohamed Ibrahim

Mohamed Ibrahim @moibra

About: Full stack web developer and Technical writer. I teach JavaScript & React & Python & Java

Joined:
Jun 3, 2021

How to loop through object - JavaScript

Publish Date: Jan 28 '23
12 12

In this article we will learn how to loop through object.

It is very common to iterate over an object in JavaScript.

There is more than one way to do this, and in this lesson we will discuss all the ways.

Methods that can be used to loop through objects in JavaScript:

  • For loop
  • for … in
  • Object.keys method
  • Object.values method
  • Object.entries method

Problem

We must understand the problem first before solving it. We want to iterate on the object right?

Now imagine that there is an object like this:

const myObject = {
    name: "John",
    age: 30,
}
Enter fullscreen mode Exit fullscreen mode

And we want to iterate over the elements to give us this output:

name John
age 30
Enter fullscreen mode Exit fullscreen mode

How do you solve that problem?

As we said before, there is more than one solution


How to loop through an object with for…in loop

We can use for .. in loop to iterate over the object keys.

Example

// Object
const myObject = {
    name: "John",
    age: 30,
}

// Print keys
for(const key in myObject) {
    console.log(key);
}
Enter fullscreen mode Exit fullscreen mode

Output

name
age
Enter fullscreen mode Exit fullscreen mode

Well, now we have half the solution, which is to print the keys, but what about the values?

// Object
const myObject = {
    name: "John",
    age: 30,
}

// Print keys & values
for(const key in myObject) {
    console.log(key, myObject[key]);
}
Enter fullscreen mode Exit fullscreen mode

Output

name John
age 30
Enter fullscreen mode Exit fullscreen mode

Yay 🚀🚀!


How to loop through an object with Object.keys() method

We can use Object.keys method to iterate over the object keys as well.

It takes the object that you want to loop over as an argument and returns an array of keys.

Example

// Object
const myObject = {
    name: "John",
    age: 30,
}

// Keys
const keys = Object.keys(myObject);

// Print Keys
console.log(keys);
Enter fullscreen mode Exit fullscreen mode

Output

[ 'name', 'age' ]
Enter fullscreen mode Exit fullscreen mode

As you can see, it returned an array with all the keys, and this means that we can iterate over the array in any way.

// Object
const myObject = {
    name: "John",
    age: 30,
}

// Array of keys
const keys = Object.keys(myObject);

// Iterate over keys with `forEach`
keys.forEach(key => {
    console.log(key);
});
Enter fullscreen mode Exit fullscreen mode

Output

name
age
Enter fullscreen mode Exit fullscreen mode

Well, now half of the problem is solved, because we made iterations on the keys, but what about the values?

As long as we can return the keys, the values will be easy to get.

Example

// Object
const myObject = {
    name: "John",
    age: 30,
}

// Array of keys
const keys = Object.keys(myObject);

// Get keys and values of object
keys.forEach(key => {
    console.log(key, myObject[key])
});
Enter fullscreen mode Exit fullscreen mode

Output

name John
age 30
Enter fullscreen mode Exit fullscreen mode

Yay 🚀🚀!


How to loop through an object with Object.values() method

We can use Object.values() method to itrate over object values.

The Object.values() method returns an array of a given object's own enumerable string-keyed property values.(Source: MDN)

Example

// Object
const myObject = {
    name: "John",
    age: 30,
}

// Array of values
const values = Object.values(myObject);

// Iterate over values
values.forEach((value) => {
    console.log(value)
});
Enter fullscreen mode Exit fullscreen mode

Output

John
30
Enter fullscreen mode Exit fullscreen mode

How to loop through an object with Object.entries() method

We can use Object.entries to iterate over the object keys and values.

The Object.entries() method returns an array of a given object's own enumerable string-keyed property key-value pairs.(Source: MDN)

Example

// Object
const myObject = {
    name: "John",
    age: 30,
}

// Array of keys and values
const entries = Object.entries(myObject);

// Iterate
for (let i = 0; i < entries.length; i++) {
    for (let n = 0; n < entries[i].length; n++) {
        console.log(entries[i][n]);
    }
}
Enter fullscreen mode Exit fullscreen mode

Output

name
John
age
30
Enter fullscreen mode Exit fullscreen mode

Thank you for reading

Thank you for reading my blog. 🚀 You can find more on my blog and connect on Twitter

Comments 12 total

  • Medea
    MedeaJan 28, 2023

    this is really helpful!

  • Jan Küster 🔥
    Jan Küster 🔥Jan 28, 2023

    Note that there are different scopes for these loops.

    for..in

    The for...in statement iterates over all enumerable string properties of an object (ignoring properties keyed by symbols), including inherited enumerable properties.

    Object.keys

    The Object.keys() static method returns an array of a given object's own enumerable string-keyed property names.

    Depending on the objects structure you may get totally different (and unexpected) results.

  • АнонимJan 28, 2023

    [deleted]

  • Ekaterine Mitagvaria
    Ekaterine MitagvariaJan 28, 2023

    Nice post, thank you!

  • script-neutron
    script-neutronJan 29, 2023

    Using entries seems a hustle 😅

    • dserv-nh
      dserv-nhJan 31, 2023

      It's really not if you just need the key/value pairs. See the MDN Example

      const object1 = {
        a: 'somestring',
        b: 42
      };
      
      for (const [key, value] of Object.entries(object1)) {
        console.log(`${key}: ${value}`);
      }
      
      // Expected output:
      // "a: somestring"
      // "b: 42"
      
      Enter fullscreen mode Exit fullscreen mode
  • Parth
    ParthFeb 1, 2023

    Nice one :) Earlier looked for some similar and easy to understood tut, but couldn't find it. Thanks

Add comment