JavaScript Object.values()

The Object.values() method returns an array containing the enumerable values of an object.

Example

// array-like object having integers as key
const obj = { 65: "A", 66: "B", 67: "C" };

// print the enumerable values of obj
console.log(Object.values(obj));

// Output:  [ 'A', 'B', 'C' ]

values() Syntax

The syntax of the values() method is:

Object.values(obj)

The values() method, being a static method, is called using the Object class name.


values() Parameters

The values() method takes in:

  • obj - the object whose enumerable properties are to be returned

values() Return Value

The values() method returns an array of strings that represents all the enumerable property values of the given object.


Example 1: Javascript Object.values() With Array-like Object

// array-like object having integers as key
const obj = { 65: "A", 66: "B", 67: "C" };

// print the enumerable values of obj console.log(Object.values(obj));
// Output: [ 'A', 'B', 'C' ]

In the above example, we have used an array-like object obj with the values() method, which returns an array of strings containing all the enumerable values.

Note: An array-like object has indexed properties and a length, but may not have all the methods and properties of an actual array.


Example 2: values() With Array Object

// an array of strings
const arr = ["JavaScript", "Python", "C"];

// print the enumerable values of the array object console.log(Object.values(arr));
// Output: [ 'JavaScript', 'Python', 'C' ]

In the above example, we have used an array of strings with the values() method, which returns an array of strings. These strings are all the enumerable property values of the array.


Example 3: values() With Object Having Random Key Ordering

// object with random key ordering
const obj1 = { 42: "a", 22: "b", 71: "c" };

// print the enumerable values of obj1 console.log(Object.values(obj1));
// Output: ['b', 'a', 'c']

In the above example, obj1 is an array that contains integer keys arranged in random order.

However, the values() method returns the values in ascending order of their corresponding keys. In other words, the value corresponding to the smallest integer key (22), which is b, is placed first, and so on.


Example 4: JavaScript Object.values() With String

const string = "code";
console.log(Object.values(string));

// values() with string returns an array of characters
// Output:  [ 'c', 'o', 'd', 'e' ]

Note: The ordering of the properties is the same as that when looping over them manually.


Recommended Reading:

Did you find this article helpful?