Modelo

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

Looping Through Objects in JavaScript

Oct 04, 2024

One of the most common tasks in JavaScript is iterating through objects to access and manipulate their properties and values. In this article, we'll explore different methods for looping through objects in JavaScript.

Method 1: for...in Loop

The for...in loop is a simple and effective way to loop through all the enumerable properties of an object. Here's an example of how to use a for...in loop to iterate through an object:

```javascript

const person = {

name: 'John',

age: 30,

profession: 'engineer'

};

for (let key in person) {

console.log(key + ': ' + person[key]);

}

```

In this example, the for...in loop iterates through the person object and logs each property and its value to the console.

Method 2: Object.keys() Method

The Object.keys() method returns an array of a given object's own enumerable property names. You can then use a for...of loop to iterate through the array of property names and access the corresponding values from the object. Here's an example:

```javascript

const car = {

make: 'Toyota',

model: 'Camry',

year: 2020

};

for (let key of Object.keys(car)) {

console.log(key + ': ' + car[key]);

}

```

In this example, we use Object.keys() to get an array of property names from the car object, and then loop through the array to access and log the properties and values.

Method 3: Object.entries() Method

The Object.entries() method returns an array of a given object's own enumerable property [key, value] pairs. You can use a for...of loop to iterate through the array of [key, value] pairs and access both the property name and value. Here's an example:

```javascript

const fruit = {

name: 'apple',

color: 'red',

flavor: 'sweet'

};

for (let [key, value] of Object.entries(fruit)) {

console.log(key + ': ' + value);

}

```

In this example, we use Object.entries() to get an array of [key, value] pairs from the fruit object, and then loop through the array to access and log both the property names and values.

In conclusion, there are multiple ways to loop through objects in JavaScript, including using for...in loops, Object.keys() method, and Object.entries() method. Each method has its own advantages and use cases, so choose the one that best suits your specific needs when working with objects in JavaScript.

Recommend