Modelo

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

How to Get the Values of an Object in JavaScript

Oct 12, 2024

When working with JavaScript objects, there may come a time when you need to retrieve the values associated with the keys. While it's relatively straightforward to access the keys of an object, getting the corresponding values requires a different approach. In this article, we'll explore several methods and techniques for getting the values of an object in JavaScript.

Method 1: Object.values()

One of the easiest ways to get the values of an object in JavaScript is to use the Object.values() method. This method was introduced in ECMAScript 2017 and returns an array of a given object's own enumerable property values. Here's an example of how to use Object.values():

const myObject = { key1: 'value1', key2: 'value2', key3: 'value3' };

const valuesArray = Object.values(myObject);

console.log(valuesArray); // Output: ['value1', 'value2', 'value3']

Method 2: Using a for...in loop

Another approach to retrieve the values of an object is to iterate through the object using a for...in loop and push the values into an array. Here's how you can accomplish this:

const myObject = { key1: 'value1', key2: 'value2', key3: 'value3' };

const valuesArray = [];

for (let key in myObject) {

valuesArray.push(myObject[key]);

}

console.log(valuesArray); // Output: ['value1', 'value2', 'value3']

Method 3: Object.entries() with map()

You can also use the Object.entries() method to get an array of key-value pairs from the object and then use the map() method to extract only the values. Here's an example:

const myObject = { key1: 'value1', key2: 'value2', key3: 'value3' };

const valuesArray = Object.entries(myObject).map(([key, value]) => value);

console.log(valuesArray); // Output: ['value1', 'value2', 'value3']

In Conclusion

Retrieving the values of an object in JavaScript is an essential skill for any developer working with objects. By using the Object.values() method, for...in loop, or Object.entries() with map(), you can efficiently access the values associated with the keys of an object. Whether you're building a web application, writing server-side code, or working on a client-side project, knowing how to get the values of an object will come in handy. Try out these methods and choose the one that best fits your coding style and project requirements.

Recommend