How do I loop through or enumerate a JavaScript object?
I have a JavaScript object like the following:
var p = {
"p1": "value1",
"p2": "value2",
"p3": "value3"
};
How do I loop through all of p’s elements (p1, p2, p3…) and get their keys and values?
To loop through a JavaScript object and access both keys and values, you can use several approaches including the for...in loop, Object.keys(), Object.values(), and Object.entries() methods. The most modern and concise approach is using Object.entries() with array iteration methods, while the for...in loop offers traditional compatibility with all browsers.
Contents
- Using for…in Loop
- Object.keys() Method
- Object.values() Method
- Object.entries() Method
- Browser Compatibility
- Performance Considerations
- Best Practices
Using for…in Loop
The for...in statement iterates over all enumerable string properties of an object, including inherited properties. This is the traditional way to loop through objects and works across all browsers.
var p = {
"p1": "value1",
"p2": "value2",
"p3": "value3"
};
for (let key in p) {
console.log(key + ": " + p[key]);
// Output:
// p1: value1
// p2: value2
// p3: value3
}
Important: The for...in loop also enumerates properties from the prototype chain, so you should check if the property belongs to the object itself using hasOwnProperty():
for (let key in p) {
if (p.hasOwnProperty(key)) {
console.log(key + ": " + p[key]);
}
}
The for...in loop has been available across browsers since July 2015 and is well-established, making it a reliable choice for most projects source.
Object.keys() Method
Object.keys() returns an array of a given object’s own enumerable property names, in the same order as that provided by a for...in loop.
var p = {
"p1": "value1",
"p2": "value2",
"p3": "value3"
};
var keys = Object.keys(p);
console.log(keys); // ["p1", "p2", "p3"]
keys.forEach(function(key) {
console.log(key + ": " + p[key]);
});
You can also use it with modern array methods:
Object.keys(p).forEach(key => {
console.log(`${key}: ${p[key]}`);
});
This method is particularly useful when you only need the keys and not the values. According to the Mozilla Developer Network, Object.keys() was introduced in ES6 to make object iteration more convenient.
Object.values() Method
Object.values() returns an array of a given object’s own enumerable property values, in the same order as that provided by a for...in loop.
var p = {
"p1": "value1",
"p2": "value2",
"p3": "value3"
};
var values = Object.values(p);
console.log(values); // ["value1", "value2", "value3"]
values.forEach(value => {
console.log(value);
});
This method is perfect when you only need the values and don’t care about the keys. As stated in the MDN documentation, the order of the array returned by Object.values() is the same as that provided by a for...in loop.
Object.entries() Method
Object.entries() returns an array of a given object’s own enumerable string-keyed [key, value] pairs. This is the most modern and often the most convenient method for accessing both keys and values.
var p = {
"p1": "value1",
"p2": "value2",
"p3": "value3"
};
// Convert object to array of [key, value] pairs
var entries = Object.entries(p);
console.log(entries);
// [["p1", "value1"], ["p2", "value2"], ["p3", "value3"]]
// Use for...of loop to iterate
for (const [key, value] of Object.entries(p)) {
console.log(`${key}: ${value}`);
// Output:
// p1: value1
// p2: value2
// p3: value3
}
// Use forEach method
Object.entries(p).forEach(([key, value]) => {
console.log(`${key}: ${value}`);
});
The Object.entries() method was introduced in ECMAScript 2017 and provides a clean, modern way to iterate through objects. As mentioned in the MDN documentation, this method returns an array of a given object’s own enumerable string-keyed property [key, value] pairs.
Browser Compatibility
Different methods have varying levels of browser support:
- for…in loop: Works in all browsers, including Internet Explorer 5.5+
- Object.keys(): Supported in IE9+ and all modern browsers
- Object.values(): Supported in IE11+ and all modern browsers
- Object.entries(): Not supported in IE11, requires modern browsers
For maximum compatibility, especially when supporting older browsers, you might need polyfills:
// Polyfill for Object.entries if not supported
if (!Object.entries) {
Object.entries = function(obj) {
var ownProps = Object.keys(obj),
i = 0,
resArray = new Array(ownProps.length),
prop;
while (i < ownProps.length) {
resArray[i] = [ownProps[i], obj[ownProps[i]]];
i++;
}
return resArray;
};
}
Performance Considerations
Different iteration methods have different performance characteristics:
- for…in loop: Generally fast but slower when dealing with large objects with many inherited properties
- Object.keys(): Creates an intermediate array of keys, slightly more memory usage
- Object.values(): Creates an intermediate array of values
- Object.entries(): Creates an intermediate array of [key, value] pairs, highest memory usage but most convenient
For performance-critical applications with large objects, the traditional for...in loop might be slightly faster, but the difference is usually negligible for most use cases.
Best Practices
Here are some recommendations for choosing the right iteration method:
-
Use for…in loop when:
- You need maximum browser compatibility
- You’re dealing with objects that might have inherited properties you want to check
- Performance is critical and you’re working with very large objects
-
Use Object.keys() when:
- You only need the keys
- You’re working with modern browsers
- You want to use array methods like
map(),filter(), etc.
-
Use Object.values() when:
- You only need the values
- You’re working with modern browsers
- You want to transform or process values using array methods
-
Use Object.entries() when:
- You need both keys and values
- You’re working with modern browsers
- You want the cleanest, most modern syntax
For your specific example object, the Object.entries() approach provides the most readable and modern solution:
var p = {
"p1": "value1",
"p2": "value2",
"p3": "value3"
};
Object.entries(p).forEach(([key, value]) => {
console.log(`${key}: ${value}`);
});
This approach is concise, easy to read, and leverages modern JavaScript features for clean object iteration.
Sources
- Object.entries() - JavaScript | MDN
- Object.keys() - JavaScript | MDN
- Object.values() - JavaScript | MDN
- for…in - JavaScript | MDN
- How do I loop through or enumerate a JavaScript object? - Stack Overflow
- How to loop through objects keys and values in Javascript? - Hostman
- How to Iterate Over a JavaScript Object? - LateNode
Conclusion
Looping through JavaScript objects can be accomplished using several methods, each with its own advantages:
- for…in loop offers the best compatibility and works with inherited properties
- Object.keys() is perfect when you only need property names
- Object.values() is ideal for accessing only property values
- Object.entries() provides the most modern and convenient approach for accessing both keys and values
For most modern JavaScript development, Object.entries() with array iteration methods like forEach() or for...of loops offers the best combination of readability and functionality. However, when supporting older browsers or working with objects that may have inherited properties, the traditional for...in loop remains a reliable choice.
Choose the method that best fits your specific needs regarding browser compatibility, code readability, and whether you need keys, values, or both.