How to loop through object entries - JavaScript

Mo Ibra

Mo Ibra

Dec 9, 2022

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

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

To iterate over objects entries we will use Object.entries method.

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


Problem

Now we want to iterate over the entries of the object.

Imagine you have an object like this:

const myObj = {
    name: "John",
    age: 30,
}

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

[ [ 'name', 'John' ], [ 'age', 30 ] ]

How do you solve that problem?

As we said before, we will use Object.entries to solve this problem.


How to iterate over an object entries using Object.entries method

Example

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

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

// Print entries
console.log(entries);

Output

[ [ 'name', 'John' ], [ 'age', 30 ] ]

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

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]);
    }
}

Output

name
John
age
30

Thank you for reading

Thank you for reading my blog. 🚀

Suggestions For More Articles: