Convert an Array of Objects to Array of Values in JS

avatar

Borislav Hadzhiev

Thu Nov 04 20212 min read

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 #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee