How to loop through a JavaScript object

October 12, 2022 No comments javascript loops for-loop each

Introduction

In JavaScript, we may wish to loop through an object. In this post, we'll look at how to do it.

How to loop through a JavaScript object?

To loop through a JavaScript object we can use several methods such as: Object.keys(obj), for...of, Object.entries() or for...of.

To iterate over object properties we can use Object.keys() combined with and Array.prototype.forEach() method

const obj = {
    name: 'John',
    surname: 'Doe'
};

Object.keys(obj).forEach(function(key) {
    console.log(key, obj[key]);
});

To loop through an Object in JavaScript we can use for...of introduced in ECMAScript 6

const obj = {
    name: 'John',
    surname: 'Doe'
};

for (const key of Object.keys(obj)) {
    console.log(key, obj[key]);
}

Iterating over an Object's properties could be achieved with Object.entries() method from ECMAScript 8

const obj = {
    name: 'John',
    surname: 'Doe'
};

Object.entries(obj).forEach(
    ([key, value]) => console.log(key, value)
);

The for...of loop combined with destructuring, and Object.entries:

const obj = {
    name: 'John',
    surname: 'Doe'
};

for (const [key, value] of Object.entries(obj)) {
    console.log(key, value);
}

There is also an old fashioned way to iterate over an object in JavaScript

var obj = {
    name: 'John',
    surname: 'Doe'
};

for (var key in obj) {
    if (obj.hasOwnProperty(key)) {
        console.log(key + " -> " + obj[key]);
    }
}

Conclusion

In this article, we learned how to loop through a JavaScript object. As you can see there are several methods to do it, you can choose the best that fits your needs.

{{ message }}

{{ 'Comments are closed.' | trans }}