Categories
JavaScript Answers

How to Extract a Value of a Property as an Array From an Array of JavaScript Objects?

Spread the love

Extracting a property value from an array of JavaScript objects is something that we’ve 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.

So we can just get foo and return it.

Lodash

We can also use Lodash methods to do the same thing.

We can use the pluck method to map an array of objects to an object with the property value of a given property from each object in the array.

For instance, we can write:

const objArray = [{
  foo: 1
}, {
  foo: 2
}, {
  foo: 3
}]
const result = _.pluck(objArray, 'foo');

In the last line, we pass in objArray , which is the object array.

And the second has the argument of the property we want to get from each object in the array.

Therefore, result should give us the same answer as in the previous examples.

Lodash also has a map method to let us do the same thing.

For instance, we write:

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

The arguments are the same as the ones taken by pluck and it returns the same result.

The latest version of Lodash also comes with the property method which we can combine with the map method by writing:

const objArray = [{
  foo: 1
}, {
  foo: 2
}, {
  foo: 3
}]
const result = _.map(objArray, _.property('foo'));

property returns an accessor a given property name we pass into the method.

And the accessor is recognized by map and it’ll use the accessor to extract the property from each object in the array.

Therefore, we get the same result as the other examples.

Conclusion

We can use plain JavaScript or Lodash to extract the value of a property from each object in an array.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *