To loop through or enumerate the properties of a JavaScript object, you can use several methods depending on your needs. Here are the most common approaches:
1. for...in
Loop
Iterates over enumerable properties (including inherited ones, unless filtered).
const obj = { a: 1, b: 2, c: 3 };
for (const key in obj) {
if (obj.hasOwnProperty(key)) { // Check to exclude inherited properties
console.log(`Key: ${key}, Value: ${obj[key]}`);
}
}
Output:
Key: a, Value: 1
Key: b, Value: 2
Key: c, Value: 3
2. Object.keys()
Returns an array of the object’s own enumerable property names.
const obj = { a: 1, b: 2, c: 3 };
Object.keys(obj).forEach(key => {
console.log(`Key: ${key}, Value: ${obj[key]}`);
});
3. Object.values()
Returns an array of the object’s own enumerable property values (ES2017+).
const obj = { a: 1, b: 2, c: 3 };
Object.values(obj).forEach(value => {
console.log(`Value: ${value}`);
});
4. Object.entries()
Returns an array of [key, value]
pairs (ES2017+).
const obj = { a: 1, b: 2, c: 3 };
// Using for...of with destructuring:
for (const [key, value] of Object.entries(obj)) {
console.log(`Key: ${key}, Value: ${value}`);
}
// Or with forEach:
Object.entries(obj).forEach(([key, value]) => {
console.log(`Key: ${key}, Value: ${value}`);
});
Key Differences
Method | Returns | Includes Inherited Properties? | ES Version |
---|---|---|---|
for...in | Keys of enumerable properties | Yes (unless filtered) | ES1 |
Object.keys() | Array of keys | No (only own properties) | ES5 |
Object.values() | Array of values | No | ES2017 |
Object.entries() | Array of [key, value] pairs | No | ES2017 |
When to Use Which?
for...in
: Rarely needed today. Use only if you need to include inherited properties (and filter withhasOwnProperty
).Object.keys/values/entries
: Preferred for modern code. Safer and more declarative.Object.entries
: Best for iterating over both keys and values.
Example: Convert Object to Map
const obj = { a: 1, b: 2 };
const map = new Map(Object.entries(obj));
console.log(map.get('a')); // 1
Notes
- Non-enumerable properties (e.g., methods from
Object.defineProperty
) won’t appear in these loops. UseObject.getOwnPropertyNames()
to include them. - Symbols: Use
Object.getOwnPropertySymbols()
to iterate over symbol-keyed properties.