Extracting a property value from an array of JavaScript objects is something that we have to do often.

In this article, we’ll look at how to create an array from property values extracted from an array of JavaScript objects.

The Array map Method

The map method is available in a JavaScript array instance that lets us map one array to another.

This means we can use it to extract property from each object in the array and put the extracted values in its own array.

For instance, we can write:

const objArray = [{
  foo: 1
}, {
  foo: 2
}, {
  foo: 3
}]
const result = objArray.map(a => a.foo);

We have the objArray array with objects with the foo property.

Then we call map with a function to return the value of the foo property from each array element.

a is the array element being iterated through.

Therefore, result is [1, 2, 3] .

We can also write:

const objArray = [{
  foo: 1
}, {
  foo: 2
}, {
  foo: 3
}]
const result = objArray.map(({
  foo
}) => foo)

In the map callback, we destructure the a object with the parameter.

#coding #programming #javascript #web-development

How to Extract the Value of a Property as an Array From an Array of JavaScript Objects
1.60 GEEK