Get an Object's Values as Array in JavaScript

avatar

Borislav Hadzhiev

2 min

banner

Photo from Unsplash

Get an Object's Values as an Array in JavaScript #

Use the Object.values() method to get an object's values as an array, e.g. const values = Object.values(obj);.

The method returns an array containing the object's property values in the same order as provided by a for ... in loop.

index.js
const obj = {id: 1, country: 'Chile', city: 'Santiago'}; const values = Object.values(obj); // ๐Ÿ‘‡๏ธ [1, 'Chile', 'Santiago'] console.log(values);

We used the Object.values() method to get the object's values as an array.

Alternatively, you can use the Object.keys() method.

Get an Object's Values as an Array using Object.keys() #

To get an object's values as an array:

  1. Use the Object.keys() method to get an array of the object's keys.
  2. Use the Array.map() method to iterate over the array.
  3. Access the object at each key and return each value.
index.js
const obj = {id: 1, country: 'Chile', city: 'Santiago'}; // ๐Ÿ‘‡๏ธ ['id', 'country', 'city'] const keys = Object.keys(obj); console.log(keys); const values = keys.map(key => { return obj[key]; }); // ๐Ÿ‘‡๏ธ [1, 'Chile', 'Santiago'] console.log(values);

We used the Object.keys() method to get an array containing the object's keys.

index.js
const obj = {id: 1, country: 'Chile', city: 'Santiago'}; // ๐Ÿ‘‡๏ธ ['id', 'country', 'city'] const keys = Object.keys(obj); console.log(keys);

The next step is to iterate over the array of keys using Array.map() and return the value of each key.

The function we passed to the Array.map() method gets invoked for each key in the keys array.

The Array.map() method returns a new array containing the values we returned from the callback function.

This approach is a bit more indirect and verbose and should only be used if you have to support very old browsers like Internet Explorer.

An alternative approach used to get an object's values as an array is to use a for...in loop.

Get an Object's Values as an Array using for...in loop #

To get an object's values as an array:

  1. Use a for...in loop to iterate over the object.
  2. Use the current key to get the current value.
  3. Push each value into an array.
index.js
const obj = {id: 1, country: 'Chile', city: 'Santiago'}; const valuesArray = []; for (const key in obj) { valuesArray.push(obj[key]); } // ๐Ÿ‘‡๏ธ [ 1, 'Chile', 'Santiago' ] console.log(valuesArray);

We used the for...in loop to iterate over the object.

On each iteration, we use the current key to get the value and push the value into a new array.

Which approach you pick is a matter of personal preference. I'd use the Object.values() method as it is quite direct and intuitive.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2023 Borislav Hadzhiev