How to loop through Object in JavaScript? [7 Methods]


Written by - Olorunfemi Akinlua
Reviewed by - Deepak Prasad

In JavaScript, objects are a fundamental data structure used to store collections of key-value pairs. They are often used to represent real-world entities such as users, products, and orders in web applications. When working with objects, it's common to need to loop through the properties and values in order to perform operations on them.

When iterating over an object, it's important to consider its properties' enumerability and prototype chain. Some methods only iterate over the object's own properties and do not include inherited properties from the prototype chain. Other methods include all properties, including inherited ones. Knowing the differences between these methods is crucial when dealing with complex object structures.

 

Different methods to loop through Object in JavaScript

There are different ways to loop through objects in JavaScript, and each method has its own advantages and use cases. Here are the most common methods:

  1. for...in loop
  2. Object.keys() method with forEach() loop
  3. Object.entries() method with forEach() loop
  4. Using a for...of loop with Object.entries()
  5. Object.getOwnPropertyNames() method with forEach() loop
  6. Object.getOwnPropertySymbols() method with forEach() loop
  7. Reflect.ownKeys() method with forEach() loop

I have you know the difference between JavaScript forEach vs forIn

 

Method-1: Using a for...in loop

The for...in loop is a common way to iterate over an object's properties in JavaScript. This loop iterates over all enumerable properties, including inherited properties. Using this approach allows us to access the properties and use them as we wish. The non-enumerable properties are often not necessary to be looped through as they are often functions or prototypes features.

Here is an example on how to loop through objects using the for...in loop method

const obj = {
    complexity: 2,
    condition: true,
    blog: "GoLinux",
    language: ["JavaScript", ""]
};

for (const element in obj) {
    console.log(`${element}: ${obj[element]}`);
}

Output

complexity: 2
condition: true
blog: GoLinux
language: JavaScript,

In the example above, we define an object obj with four properties (complexity, condition, blog, and language). We then use a for...in loop to iterate over each property in the object and print its name and value to the console.

 

Method-2: Using Object.keys() and forEach()

You can also use the Object.keys() method to get an array of an object's own enumerable properties, and then use the forEach() method to loop through each property.

const obj = {
    complexity: 2,
    condition: true,
    blog: "GoLinux",
    language: ["JavaScript", ""],
};

Object.keys(obj).forEach((prop) => {
    console.log(`${prop}: ${obj[prop]}`);
});

Output:

complexity: 2
condition: true
blog: GoLinux
language: JavaScript,

In this example, we use the Object.keys() method to get an array of the object's own enumerable properties (complexity, condition, blog, and language). We then use the forEach() method to loop through each property and print its name and value to the console.

 

Method-3: Using Object.entries() and forEach()

Another way to loop through an object's properties is to use the Object.entries() method to get an array of key-value pairs, and then use the forEach() method to loop through each pair.

const obj = {
    complexity: 2,
    condition: true,
    blog: "GoLinux",
    language: ["JavaScript", ""],
};

Object.entries(obj).forEach(([prop, value]) => {
    console.log(`${prop}: ${value}`);
});

Output:

complexity: 2
condition: true
blog: GoLinux
language: JavaScript,

In this example, we use the Object.entries() method to get an array of key-value pairs for the object ([["complexity", 2], ["condition", true], ["blog", "GoLinux"], ["language", "['JavaScript, '']"]). We then use the forEach() method to loop through each pair and print the key-value pair to the console.

 

Method-4: Using a for...of loop with Object.entries()

You can also use a for...of loop with the Object.entries() method to loop through an object's key-value pairs.

const obj = {
    complexity: 2,
    condition: true,
    blog: "GoLinux",
    language: ["JavaScript", ""],
};

for (const [prop, value] of Object.entries(obj)) {
    console.log(`${prop}: ${value}`);
}

Output:

complexity: 2
condition: true
blog: GoLinux
language: JavaScript,

In this example, we use a for...of loop to iterate over the array returned by the Object.entries() method. This method returns an array of arrays, where each inner array contains two elements: the property name and its corresponding value. This approach is similar to using forEach() with Object.entries(), but it uses a for...of loop instead.

 

Method-5: Using Object.getOwnPropertyNames() method with forEach() loop

The Object.getOwnPropertyNames() method returns an array of all properties (enumerable or not) of an object, including properties on the object's prototype chain. To loop through the properties of an object using this method, you can use a forEach() loop on the returned array of property names. Here's an example:

const person = {
  name: 'John',
  age: 30,
  getFullName() {
    return `${this.name} Doe`;
  }
};

Object.getOwnPropertyNames(person).forEach(propertyName => {
  console.log(`${propertyName}: ${person[propertyName]}`);
});

In this example, we define an object person with three properties: name, age, and getFullName. We use Object.getOwnPropertyNames() to get an array of all property names on the person object and then loop through that array using forEach(). Inside the loop, we log each property name and its value to the console.

Output

name: John
age: 30
getFullName: function getFullName() { return `${this.name} Doe`; }

 

Method-6: Using Object.getOwnPropertySymbols() method with forEach() loop

The Object.getOwnPropertySymbols() method returns an array of all symbol properties of an object, including symbol properties on the object's prototype chain. To loop through the symbol properties of an object using this method, you can use a forEach() loop on the returned array of symbol properties. Here's an example:

const age = Symbol('age');
const person = {
  name: 'John',
  [age]: 30
};

Object.getOwnPropertySymbols(person).forEach(symbol => {
  console.log(`${symbol.toString()}: ${person[symbol]}`);
});

In this example, we define an object person with two properties: name and a symbol property age. We use Object.getOwnPropertySymbols() to get an array of all symbol properties on the person object and then loop through that array using forEach(). Inside the loop, we log each symbol property and its value to the console.

Output

Symbol(age): 30

 

Method-7: Reflect.ownKeys() method with forEach() loop

The Reflect.ownKeys() method returns an array of all property keys (including symbol keys) of an object, including keys on the object's prototype chain. To loop through all keys of an object, including both string and symbol keys, you can use a forEach() loop on the returned array of keys. Here's an example:

const age = Symbol('age');
const person = {
  name: 'John',
  [age]: 30
};

Reflect.ownKeys(person).forEach(key => {
  console.log(`${key.toString()}: ${person[key]}`);
});

In this example, we define an object person with two properties: name and a symbol property age. We use Reflect.ownKeys() to get an array of all keys on the person object and then loop through that array using forEach(). Inside the loop, we log each key and its value to the console.

name: John
Symbol(age): 30

 

Summary

Looping through objects is a common task in JavaScript, and there are various methods to achieve this. The most commonly used method is the for...in loop, which iterates over all enumerable properties of an object, including those in the prototype chain. However, this method doesn't include non-enumerable properties and can also be slow when used with complex object structures.

The Object.keys() method returns an array of all enumerable properties of an object, and can be used in conjunction with a forEach() loop to iterate through them. Similarly, the Object.entries() method returns an array of key-value pairs for all enumerable properties, which can also be looped through with forEach().

For more advanced cases, there are methods such as Object.getOwnPropertyNames(), Object.getOwnPropertySymbols(), and Reflect.ownKeys(). Object.getOwnPropertyNames() returns an array of all properties, including non-enumerable ones, while Object.getOwnPropertySymbols() returns an array of symbol properties. Both of these methods can be used with a forEach() loop. Reflect.ownKeys() returns an array of all keys, including symbol keys, and can also be looped through with forEach().

 

ReferencesReflect.ownKeys

Object.keys() - JavaScript | MDN (mozilla.org)
Object.entries() - JavaScript | MDN (mozilla.org)

 

Olorunfemi Akinlua

He is boasting over five years of experience in JavaScript, specializing in technical content writing and UX design. With a keen focus on programming languages, he crafts compelling content and designs user-friendly interfaces to enhance digital experiences across various domains. You can connect with him on LinkedIn.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

Leave a Comment