Borislav Hadzhiev
Last updated: Feb 23, 2022
Photo from Unsplash
Use the map()
method to get an array of values from an array of objects,
e.g. arr.map((obj) => obj.id)
. The map
method will return a new array
containing only the values you returned from the callback function you passed to
the method.
const arr = [ { id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }, { id: 3, name: 'Carl' }, ]; const ids = arr.map((obj) => obj.id); console.log(ids); // 👉️ [1, 2, 3] const names = arr.map((obj) => obj.name); console.log(names); // 👉️ ['Alice', 'Bob', 'Carl']
The function we passed to the Array.map method gets called with each element (object) in the array.
map
method returns an array that contains the values you returned from the callback function.We used an implicit return in the examples, but you can also use a function with a body and explicit return.
const arr = [ { id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }, { id: 3, name: 'Carl' }, ]; const ids = arr.map((obj) => { return obj.id; }); console.log(ids); // 👉️ [1, 2, 3]
You can also use destructuring assignment to only get the necessary values as parameters to the function.
const arr = [ { id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }, { id: 3, name: 'Carl' }, ]; // 👇️ destructuring const ids = arr.map(({ id }) => { return id; }); console.log(ids); // 👉️ [1, 2, 3]
We destructured the id
property in the example.
An easy way to think about destructuring is - we are taking properties from the object and assigning their values to a variable.
const { id, name } = { id: 1, name: 'Alice' }; console.log(id); // 👉️ 1 console.log(name); // 👉️ "Alice"
If the specific property you are accessing is not defined on some of the objects
in the array, you might get some undefined
values in the new array.
const arr = [{ id: 1, name: 'Alice' }, { id: 2 }, { id: 3, name: 'Carl' }]; const names = arr.map((obj) => obj.name); console.log(names); // 👉️ ['Alice', undefined, 'Carl']
You can use the filter()
method to remove the undefined
values from the
array.
const arr = [{ id: 1, name: 'Alice' }, { id: 2 }, { id: 3, name: 'Carl' }]; const names = arr .map((obj) => obj.name) .filter((value) => { return value !== undefined; }); console.log(names); // 👉️ ['Alice', 'Carl']
The function we passed to the filter()
method gets called with each element in
the array.
filter()
method returns an array that contains only the values for which the callback function returned a truthy value.In the example above, these are only values that are not equal to undefined
.
This way you can be sure the array in the names
variable won't have any
undefined
values.