In JavaScript, objects are necessary for key-value pair storage. Iterating through objects is typically necessary, regardless of whether you're developing a basic application or working with intricate data from an API. In JavaScript, there are several approaches to accomplish this, and each has pros and cons of its own.
We will look at ten distinct JavaScript methods for iterating over an object in this article. For every technique, we'll offer special instances and go over when to use them.
Put your object mastery to work. Join Index.dev for long-term JavaScript remote opportunities.
1. The for...in Loop
One of the easiest methods for iterating over an object's attributes is to use a for...in loop. It runs over every property that may be listed for the object, including those that are passed down from its prototype chain.
Example:
const person = { name: 'Alice', age: 28, city: 'Berlin' };
for (let key in person) {
console.log(`${key}: ${person[key]}`);
}Pros:
- Simple and easy to understand.
- Works in all browsers.
Cons:
- Iterates over inherited properties. If you want to ignore those, you have to add a check using hasOwnProperty.
Example with hasOwnProperty:
for (let key in person) {
if (person.hasOwnProperty(key)) {
console.log(`${key}: ${person[key]}`);
}
}
2. Object.keys() with forEach()
An array with the names of an object's own properties is returned by Object.keys(). This array may be looped through using forEach().
Example:
const car = { make: 'Toyota', model: 'Camry', year: 2021 };
Object.keys(car).forEach(key => {
console.log(`${key}: ${car[key]}`);
});Pros:
- It only iterates over the object’s own properties, ignoring the prototype properties.
- Cleaner and more modern than for...in.
Cons:
- Slightly less intuitive for beginners because it involves array methods.
3. Object.values()
Use Object.values() if the values are all that matter to you and the keys are not. An array containing the values of the object's properties is returned by this function.
Example:
const user = { username: 'john_doe', email: '[email protected]', age: 35 };
Object.values(user).forEach(value => {
console.log(value);
});Pros:
- Simple when you only need the values.
- Cleaner than combining for...in with hasOwnProperty.
Cons:
- No access to the keys.
4. Object.entries()
An array of the key-value pairs for the object is returned by Object.entries(). The key and the associated value are the two elements that make up each element in this array.
Example:
const book = { title: '1984', author: 'George Orwell', year: 1949 };
Object.entries(book).forEach(([key, value]) => {
console.log(`${key}: ${value}`);
});Pros:
- You get both keys and values in a very clean way.
- Great for destructuring the key-value pair in a single line.
Cons:
- Slightly more complex compared to other methods.
5. forEach() on Arrays of Objects
ForEach() is one of the simplest methods to loop through an array of items.
Example:
const users = [
{ name: 'Alice', age: 28 },
{ name: 'Bob', age: 34 }
];
users.forEach(user => {
console.log(`${user.name}: ${user.age}`);
});Pros:
- Simple syntax and widely understood by most developers.
- Useful for arrays of objects.
Cons:
- Limited to arrays. If you're working with a single object, you can't use this directly.
Explore More: Optimising Performance with Advanced JavaScript Array Methods & Patterns
6. for...of Loop
Arrays, strings, and maps are examples of iterable objects that can be iterated over using the for...of loop. You must first transform the item into an iterable structure, such as an array, in order to utilize it with it.
Example:
const movie = { title: 'Inception', director: 'Christopher Nolan', year: 2010 };
for (const [key, value] of Object.entries(movie)) {
console.log(`${key}: ${value}`);
}Pros:
- Cleaner than for...in when combined with Object.entries().
- Allows easy destructuring within the loop.
Cons:
- Only works with iterable objects. You have to use Object.entries() to convert the object first.
7. map() Method
Usually, arrays are iterated over using the map() function, which returns a new array with the data altered. When you need to convert or return a new array from an array of objects, you may use it.
Example:
const users = [
{ name: 'Alice', age: 28 },
{ name: 'Bob', age: 34 }
];
const usernames = users.map(user => user.name);
console.log(usernames); // ['Alice', 'Bob']Pros:
- Great for transforming arrays.
- Returns a new array, which can be useful for chaining other array methods.
Cons:
- Limited to arrays.
8. reduce() Method
Every element of the array is subjected to a reducer function using the reduce() method, which produces a single output value. It's a little more intricate, but it has great data aggregation capabilities.
Example:
const expenses = { rent: 1000, groceries: 200, utilities: 150 };
const total = Object.values(expenses).reduce((sum, expense) => sum + expense, 0);
console.log(`Total expenses: $${total}`);Pros:
- Powerful for summing or accumulating object values.
- Useful for aggregating data into a single result.
Cons:
- Can be less intuitive than other methods.
9. Object.getOwnPropertyNames()
An array containing every property of an object, including non-enumerable properties, is returned by this function. If you need to access secret properties, it could be helpful.
Example:
const car = { make: 'Toyota', model: 'Corolla' };
Object.defineProperty(car, 'year', { value: 2021, enumerable: false });
const props = Object.getOwnPropertyNames(car);
props.forEach(prop => {
console.log(`${prop}: ${car[prop]}`);
});Pros:
- Retrieves non-enumerable properties.
- Useful when dealing with hidden object properties.
Cons:
- Doesn’t ignore prototype properties unless filtered manually.
10. Reflect.ownKeys()
Reflect.ownKeys() yields an object's whole set of properties, including symbol-based and non-enumerable ones. When working with symbols or hidden attributes, it is helpful.
Example:
const person = { name: 'Alice' };
const symbolKey = Symbol('age');
person[symbolKey] = 28;
const keys = Reflect.ownKeys(person);
keys.forEach(key => {
console.log(`${String(key)}: ${person[key]}`);
});Pros:
- Can access both string and symbol keys.
- Covers all properties, including hidden ones.
Cons:
- Rarely needed unless working with symbols.
Explore More: How to Migrate from Vue to React App: A Strategic Guide
Conclusion
There are several methods for iterating through objects in JavaScript, each with unique benefits and use cases. There is a way for any situation, whether it is basic key-value pairs, arrays of objects, or even objects with hidden characteristics. For more complex situations, techniques like Reflect.ownKeys() or Object.entries() provide more flexibility, but for simpler jobs, for...in or Object.keys() can be sufficient.
Try using these techniques on your own projects to see which ones suit your needs the best!
For Developers: Level up your JavaScript skills and explore global remote opportunities—join Index.dev today!
For Clients: Join Index.dev to access vetted JavaScript experts and build a high-performing tech team today with no platform fees!