Modelo

  • EN
    • English
    • Español
    • Français
    • Bahasa Indonesia
    • Italiano
    • 日本語
    • 한국어
    • Português
    • ภาษาไทย
    • Pусский
    • Tiếng Việt
    • 中文 (简体)
    • 中文 (繁體)

How to Loop Through Objects in JavaScript

Oct 06, 2024

If you're working with JavaScript objects and need to iterate over the key-value pairs, you'll need to know how to loop through objects efficiently. There are several methods to achieve this, and we'll cover some common techniques to help you master object iteration in JavaScript.

1. Using for...in Loop: The for...in loop is a simple and effective way to iterate over the properties of an object. Here's an example of how to use it:

```

const myObject = { name: 'John', age: 30, city: 'New York' };

for (let key in myObject) {

console.log(key, myObject[key]);

}

```

In this example, we use the for...in loop to iterate through the properties of `myObject`, and for each iteration, we log the key and its corresponding value to the console.

2. Using Object.keys() Method: The `Object.keys()` method returns an array of a given object's own enumerable property names. You can then loop through the array using the forEach() method or a for loop. Here's an example:

```

const myObject = { name: 'John', age: 30, city: 'New York' };

Object.keys(myObject).forEach(key => {

console.log(key, myObject[key]);

});

```

In this example, we use `Object.keys()` to get an array of keys from `myObject`, and then we loop through the keys using `forEach()` and log the key-value pairs to the console.

3. Using Object.entries() Method: The `Object.entries()` method returns an array of a given object's own enumerable property [key, value] pairs. Here's an example of how to use it:

```

const myObject = { name: 'John', age: 30, city: 'New York' };

Object.entries(myObject).forEach(([key, value]) => {

console.log(key, value);

});

```

In this example, we use `Object.entries()` to get an array of [key, value] pairs from `myObject`, and then we loop through the array using `forEach()` and log the key-value pairs to the console.

By mastering these techniques, you can effectively loop through objects in JavaScript and perform operations on object properties with ease.

Recommend