JavaScript Object.values(obj) method


The Object.values(obj) method in JavaScript is used to retrieve an array of a given object's own enumerable property values. This method is particularly useful when you want to access the values of an object without needing to know its keys.

Syntax:

const valuesArray = Object.values(obj);

Parameters:

  • obj: The object whose own enumerable property values are to be returned.

Return Value:

  • An array containing the values of the object's own enumerable properties, in the same order as they would be iterated over in a for...in loop (excluding properties inherited from the object's prototype).

Key Features:

  • Only Own Properties: Object.values() returns only the object's own properties, not properties inherited through the prototype chain.
  • Enumerable Properties: Only properties that are enumerable are included in the returned array. Non-enumerable properties are ignored.
  • Order: The order of values follows the same rules as those for for...in loops:
    • Integer keys (like 1, 2, etc.) are listed in ascending order.
    • String keys are listed in the order they were added.
    • Symbol keys are listed in the order they were added.

Example 1: Basic Usage

const person = { name: 'Alice', age: 30, job: 'Developer' }; const values = Object.values(person); console.log(values); // Output: ["Alice", 30, "Developer"]

In this example, Object.values() retrieves the values of the person object and returns them as an array.

Example 2: Using with Loop

You can use the returned array to iterate over the object's values:

const car = { make: 'Toyota', model: 'Camry', year: 2020 }; Object.values(car).forEach(value => { console.log(value); }); // Output: // Toyota // Camry // 2020

In this example, Object.values(car) returns the values of the car object, and forEach is used to log each value.

Example 3: Non-Enumerable Properties

const obj = {}; Object.defineProperty(obj, 'nonEnumerable', { value: 'I am non-enumerable', enumerable: false }); obj.enumerable = 'I am enumerable'; const values = Object.values(obj); console.log(values); // Output: ["I am enumerable"]

In this example, nonEnumerable is not included in the output because it is defined as a non-enumerable property.

Summary:

  • Object.values(obj) is a straightforward method for obtaining an array of a given object's own enumerable property values.
  • It is commonly used for iterating over an object's values or for quickly retrieving a list of values for processing.
  • Understanding this method is essential for working with objects in JavaScript, especially in situations where you need to focus on the data contained within an object rather than the keys.