Borislav Hadzhiev
Thu Nov 04 2021·2 min read
Photo by Alexandr Bormotin
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.
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.
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.
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.
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.