How to traverse object properties in js

Insert image description here

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-inloops 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:

  1. Use for-inloop :

for-inLoops 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]);
}
  1. Use Object.keys()andforEach :

Object.keys()The method returns an array containing all the keys of the object, which can then be Array.prototype.forEachiterated 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]);
});
  1. 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...inloop (the difference is that a for-in loop also enumerates properties in the prototype chain). Then use Array.prototype.forEachto iterate over this array.

let obj = {
    
     a: 1, b: 2, c: 3 };
Object.entries(obj).forEach(([key, value]) => {
    
    
    console.log(key, value);
});
  1. Use for...ofloop :

for...ofLooping is a new method of traversing arrays introduced in ES6. It can also be used to traverse the properties of objects. Its performance for-inis similar to loop.

let obj = {
    
     a: 1, b: 2, c: 3 };
for (let [key, value] of Object.entries(obj)) {
    
    
    console.log(key, value);
}
  1. Use mapandObject.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.mapand 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.

Guess you like

Origin blog.csdn.net/zhangwenok/article/details/133348854