Mastering Object Iteration in JavaScript: A Comprehensive Guide

Priti Jha
2 min readJust now

--

Efficiently working with objects is a fundamental skill for any JavaScript developer. Whether you’re traversing keys, values, or deeply nested structures, understanding different iteration techniques can significantly enhance your code’s readability and performance. This guide dives into the six most common ways to iterate through objects in JavaScript, including practical examples and best practices for working with complex data structures.

1. Using for...in Loop

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

const obj = { name: 'Alice', age: 25, city: 'New York' };

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


//Output
name: Alice
age: 25
city: New York

2. Using Object.keys()

The Object.keys() method returns an array of an object's keys. You can then use forEach() or a loop to iterate over the keys.

const obj = { name: 'Alice', age: 25, city: 'New York' };

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

3. Using Object.values()

The Object.values() method returns an array of the object's values. Iterate over them if you're only interested in the values.

const obj = { name: 'Alice', age: 25, city: 'New York' };

Object.values(obj).forEach((value) => {
console.log(value);
});

4. Using Object.entries()

The Object.entries() method returns an array of [key, value] pairs. It's useful for iterating over both keys and values.

const obj = { name: 'Alice', age: 25, city: 'New York' };

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

5. Using for...of with Object.entries()

If you prefer a for...of loop, combine it with Object.entries()

const obj = { name: 'Alice', age: 25, city: 'New York' };

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

6. Iterating Nested Objects

If the object contains nested objects, you can use recursion to iterate through them.

const nestedObj = { name: 'Alice', details: { age: 25, city: 'New York' } };

function iterate(obj) {
for (const key in obj) {
if (typeof obj[key] === 'object' && obj[key] !== null) {
iterate(obj[key]); // Recursive call
} else {
console.log(`${key}: ${obj[key]}`);
}
}
}

iterate(nestedObj);

Best Practice

  • Use Object.entries() for clean key-value pair iteration.
  • Use Object.keys() or Object.values() if you only need keys or values.
  • Use for...in cautiously as it also iterates over inherited properties unless filtered with hasOwnProperty.

--

--

Priti Jha
Priti Jha

Written by Priti Jha

Senior front-end developer writing about Angular 8 , Ionic Framework ,Javascript, HTML, Css and all front end technology.