Convert an Array of Objects to Array of Values in JS

avatar

Borislav Hadzhiev

Last updated: Nov 4, 2021

banner

Photo from Unsplash

Convert an Array of Objects to Array of Values #

To convert an array of objects to array of values, call the map() method on the array and on each iteration, return the value, e.g. arr.map(obj => obj.property). The map method will return a new array containing the corresponding values.

index.js
const arrOfObj = [ {id: 1, name: 'Alice'}, {id: 2, name: 'Bob'}, ]; const arr = arrOfObj.map(object => object.name); console.log(arr); // 👉️ ['Alice', 'Bob']

The function we passed to the Array.map method gets called with each element (object) in the array.

On each iteration, we access the object at a specific property to get an array of values.

The map() method returns a new array that contains all of the values the callback function returned.

The map method does not mutate the original array, it returns a new array.

An alternative approach is to use the Array.forEach method to iterate over the array.

index.js
const arrOfObj = [ {id: 1, name: 'Alice'}, {id: 2, name: 'Bob'}, ]; const arr = []; arrOfObj.forEach(object => { arr.push(object.name); }); console.log(arr); // 👉️ ['Alice', 'Bob']

The forEach method returns undefined, so we have to declare a variable that will store the state from iterating over the array.

The function we passed to the method gets called with each element (object) in the array.

The last step is to push the values we want to persist.

For this use case, you should use the map method because it's more direct. When using forEach, we are forced to declare an intermediate variable to store the state from looping over the array.

Further Reading #

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.