Modelo

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

Mastering Object Looping in JavaScript

Oct 16, 2024

Hey JavaScript enthusiasts! Are you ready to master the art of looping through objects? Let's dive right in!

1. Using Object.keys():

This method returns an array of a given object's own property names. You can then loop through the array using a for...of loop or forEach() method to access the object's properties and values.

Example:

```javascript

const myObj = { name: 'John', age: 30, gender: 'male' };

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

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

});

```

2. Using Object.entries():

This method returns an array of a given object's own enumerable string-keyed property [key, value] pairs. You can then use destructuring in a for...of loop to access both the key and value of each property.

Example:

```javascript

const myObj = { name: 'John', age: 30, gender: 'male' };

for (const [key, value] of Object.entries(myObj)) {

console.log(key, value);

}

```

3. Using Object.values():

This method returns an array of a given object's own enumerable property values. You can then loop through the array using a for...of loop or forEach() method to access the object's values.

Example:

```javascript

const myObj = { name: 'John', age: 30, gender: 'male' };

Object.values(myObj).forEach(value => {

console.log(value);

});

```

By mastering these techniques, you'll be able to efficiently iterate through objects in JavaScript and harness the full power of your data. Happy coding!

Recommend