Iterate Object in JavaScript

Summary: in this tutorial, you will learn various ways to iterate an object in JavaScript.

The for...in loop

The for...in loop allows you to iterate the enumerable properties of an object. In each iteration, you can get the object key and by using that you can access the property value. For example:

let person = {
    firstName: 'John',
    lastName: 'Doe',
    age: 25,
    ssn: '123-456-2356'
};

for (let key in person) {
    if (person.hasOwnProperty(key)) {
        console.log(`${key} : ${person[key]}`);
    }
}
Code language: JavaScript (javascript)

Output:

firstName : John
lastName : Doe
age : 25
ssn : 123-456-2356

This hasOwnProperty() method ensures that the property belongs to the person object, not the inherited properties.

Note that the for...in ignores properties keyed by Symbols.

 Object.keys()

The Object.keys() takes an object and returns an array of the object’s properties. By chaining the Object.keys() with the forEach() method, you can access the keys and values of an object. Note that the Object.keys() method was introduced in ES6. For example:

let person = {
    firstName: 'John',
    lastName: 'Doe',
    age: 25,
    ssn: '123-456-2356'
};

Object.keys(person).forEach(key => {
    console.log(`${key}: ${person[key]}`);
});Code language: JavaScript (javascript)

Output:

firstName: John
lastName: Doe
age: 25
ssn: 123-456-2356Code language: HTTP (http)

 Object.values()

The Object.values() takes an object as an argument and returns an array of the object’s values. The Object.entries() method has been available since ES7.

let person = {
    firstName: 'John',
    lastName: 'Doe',
    age: 25,
    ssn: '123-456-2356'
};

Object.values(person).forEach(value => {
    console.log(`${value}`);
});
Code language: JavaScript (javascript)

Output:

John
Doe
25
123-456-2356

 Object.entries()

The Object.entries() takes an object and returns an array of the object’s own enumerable string-keyed property [key, value] pairs.

let person = {
    firstName: 'John',
    lastName: 'Doe',
    age: 25,
    ssn: '123-456-2356'
};

Object.entries(person).forEach(([key, value]) => {
    console.log(`${key}: ${value}`);
});
Code language: JavaScript (javascript)

Output

firstName: John
lastName: Doe
age: 25
ssn: 123-456-2356    
Code language: HTTP (http)

Object.getOwnPropertyNames()

The Object.getOwnPropertyNames() method accepts an object as an argument and returns an array of object’s keys, including non-enumerable properties except for the ones which use Symbol.

let person = {
    firstName: 'John',
    lastName: 'Doe',
    age: 25,
    ssn: '123-456-2356'
};

Object.getOwnPropertyNames(person).forEach(key =>
    console.log(`${key}: ${person[key]}`)
);
Code language: JavaScript (javascript)

Output:

firstName: John
lastName: Doe
age: 25
ssn: 123-456-2356Code language: HTTP (http)

In this tutorial, you have learned various ways to iterate an object in JavaScript.

Was this tutorial helpful ?