Modelo

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

How to Get the Opposite of Keys in JavaScript Objects

Oct 13, 2024

When working with JavaScript objects, it’s common to need the values associated with the keys, rather than the keys themselves. Fortunately, there are several ways to achieve this in JavaScript.

One approach is to use the Object.values() method, which returns an array of a given object's own enumerable property values. Here’s an example:

```javascript

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

const values = Object.values(person);

console.log(values); // Output: ['John', 30, 'male']

```

Another method is to use the for...in loop to iterate through the object and retrieve the values. Here’s how you could do this:

```javascript

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

const values = [];

for (let key in person) {

values.push(person[key]);

}

console.log(values); // Output: ['John', 30, 'male']

```

Additionally, you can use the Object.entries() method to get both the keys and values as an array of key-value pairs. You can then use array destructuring to extract only the values. Here’s an example:

```javascript

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

const values = Object.entries(person).map(([key, value]) => value);

console.log(values); // Output: ['John', 30, 'male']

```

In some cases, you may also want to retrieve unique values from the object. You can achieve this by combining the Object.values() method with the Set object, which allows you to store unique values of any type. Here’s how it can be done:

```javascript

const person = { name: 'John', age: 30, gender: 'male', hobby: 'reading' };

const values = [...new Set(Object.values(person))];

console.log(values); // Output: ['John', 30, 'male', 'reading']

```

In conclusion, there are multiple ways to obtain the values of JavaScript objects in contrast to their keys. Whether you prefer using built-in methods such as Object.values(), iterating through the object with a for...in loop, or extracting values from key-value pairs using Object.entries(), you have several options to achieve this common programming task.

Recommend