Topic 63 of 87
Object Iteration
Overview
Unlike Arrays, standard Objects are NOT iterables. You cannot use a for...of loop or .map() on an object directly.
To iterate through an object, you must either use a for...in loop (legacy), or use modern ES6 static Object methods that convert the object's keys or values into a standard Array, which can then be iterated normally.
Syntax
Modern ES6 Static Methods
javascript
const user = { name: "Aman", age: 25, role: "Admin" };
// 1. Object.keys() returns an ARRAY of the keys (strings)
console.log(Object.keys(user));
// ["name", "age", "role"]
// 2. Object.values() returns an ARRAY of the values
console.log(Object.values(user));
// ["Aman", 25, "Admin"]
// 3. Object.entries() returns an ARRAY of [key, value] arrays
console.log(Object.entries(user));
// [ ["name", "Aman"], ["age", 25], ["role", "Admin"] ]Combining with Array Methods
javascript
// We convert it to an array, then safely use .map() or .forEach()
Object.keys(user).forEach(key => {
console.log(`Key: ${key}, Value: ${user[key]}`);
});Common Pitfalls
- Assuming Object properties are perfectly ordered. While modern JS engines sort string keys chronologically by creation, integer keys (like '1', '2') are always hoisted to the top and sorted numerically. Never rely on object insertion order; use a
Mapif order is critical.
Interview Questions
Q:
How would you find out how many properties are inside an object?
A:
Objects do not have a .length property. The standard way to get the count is to generate an array of its keys and get the length of that array: Object.keys(myObj).length.
Real-World Example
Converting a query parameters object into a URL string for an API fetch.
example
javascript
const params = { search: 'laptops', page: 2 };
const queryStr = Object.keys(params)
.map(key => `${key}=${params[key]}`)
.join('&');Check Your Knowledge
Test your understanding of Object Iteration with these quick questions.