How to Iterate Over Objects in JavaScript

In JavaScript, iterating over objects means looping through their properties. This is a common task when working with data structures. Let’s explore different methods to achieve this.

What is an Object in JavaScript?

An object is a collection of key-value pairs. For example:

const person = {
  name: 'Alice',
  age: 30,
  city: 'New York'
};

Method 1: Using for...in Loop

The for...in loop iterates over the enumerable properties of an object.

const person = { name: 'Alice', age: 30 };

for (let key in person) {
  console.log(key);  // Outputs: 'name', 'age'
}

Note: for...in includes inherited properties. To list only own properties:

for (let key in person) {
  if (person.hasOwnProperty(key)) {
    console.log(key);
  }
}

Method 2: Using Object.keys()

Object.keys() returns an array of the object’s own enumerable property keys.

const keys = Object.keys(person);
keys.forEach(key => console.log(key));

Method 3: Using Object.values()

If you need the values instead of keys:

const values = Object.values(person);
values.forEach(value => console.log(value));

Method 4: Using Object.entries()

Object.entries() returns an array of [key, value] pairs.

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

Method 5: Using Reflect.ownKeys()

For a comprehensive list including non-enumerable properties:

const allKeys = Reflect.ownKeys(person);
allKeys.forEach(key => console.log(key));

Handling Nested Objects

For nested objects, you can use recursion:

function iterateObject(obj) {
  for (let key in obj) {
    if (typeof obj[key] === 'object' && obj[key] !== null) {
      iterateObject(obj[key]);
    } else {
      console.log(`${key}: ${obj[key]}`);
    }
  }
}

const nested = { a: 1, b: { c: 2 } };
iterateObject(nested);

Frequently Asked Questions

1. Why does for...in include inherited properties?

for...in is designed to iterate over all enumerable properties, including those inherited via the prototype chain.

2. How do I iterate over values only?

Use Object.values().

3. Can I iterate over symbols?

Yes, but symbols are unique and can’t be iterated in the same way as string or number keys.

Conclusion

JavaScript provides multiple ways to iterate over objects. Choose the method based on your specific needs, such as whether you need keys, values, or both, and whether you want to include inherited properties.

Index
Scroll to Top