In JavaScript, there are many ways to iterate over an object's properties, but there is no significant difference in performance. For most use cases, using for-in
loops or Object.keys()
methods is most common.
However, if you are looking for micro-optimizations and want to iterate over a large number of objects, consider the following options to improve performance:
- Use
for-in
loop :
for-in
Loops are the basic way to iterate over the properties of an object. In older JavaScript engines, its performance may be slightly worse, but in modern engines, its performance has been optimized.
let obj = {
a: 1, b: 2, c: 3 };
for (let key in obj) {
console.log(key, obj[key]);
}
- Use
Object.keys()
andforEach
:
Object.keys()
The method returns an array containing all the keys of the object, which can then be Array.prototype.forEach
iterated over using . This approach may be slightly faster in some cases, especially when processing large amounts of data.
let obj = {
a: 1, b: 2, c: 3 };
Object.keys(obj).forEach(key => {
console.log(key, obj[key]);
});
- Use
Object.entries()
andforEach
:
Object.entries()
Returns an array of key-value pairs for the given object's own enumerable properties, arranged in the same order as using a for...in
loop (the difference is that a for-in loop also enumerates properties in the prototype chain). Then use Array.prototype.forEach
to iterate over this array.
let obj = {
a: 1, b: 2, c: 3 };
Object.entries(obj).forEach(([key, value]) => {
console.log(key, value);
});
- Use
for...of
loop :
for...of
Looping is a new method of traversing arrays introduced in ES6. It can also be used to traverse the properties of objects. Its performance for-in
is similar to loop.
let obj = {
a: 1, b: 2, c: 3 };
for (let [key, value] of Object.entries(obj)) {
console.log(key, value);
}
- Use
map
andObject.entries()
:
If you are only interested in the values of the object and want to convert them into a new array, you can use Array.prototype.map
and Object.entries()
.
let obj = {
a: 1, b: 2, c: 3 };
let values = Object.entries(obj).map(([key, value]) => value);
console.log(values); // [1, 2, 3]
Note: When iterating over an object, be careful not to modify the object itself, as this may lead to unexpected results. If you need to modify the object during the traversal, you can create a copy first.