Lodash’s _.pluck method is used to extract a list of property values from an array of objects, which has been deprecated and removed in newer versions of Lodash. Instead, Lodash now recommends using _.map a property accessor function.
These are the following topics that we are going to discuss:
What is Lodash _.pluck?Lodash _.pluck was a method in Lodash used to extract the values of a specific property from a collection of objects. For example, if we want an array of objects and want to create a new array containing only the values of a specific property from each object then we can use the _.pluck method to do it easily.
You need to install the package to run the code:
npm install lodash Note: The code below will not show the output as the recent version of Lodash does not have this function anymore.
Example: This example shows the use of the Lodash _.pluck() function.
JavaScript
const _ = require("lodash")
const people = [
{ name: 'John', age: 30 },
{ name: 'Jane', age: 25 },
{ name: 'Jack', age: 35 }
];
// Using _.pluck to get an array of names
const names = _.pluck(people, 'name');
console.log(names);
Output:
['John', 'Jane', 'Jack'] What happened to _.pluck in Lodash 4.x and Beyond?In Lodash version 4.0.0 and later, _.pluck was removed and its functionality was merged into _.map to streamline and simplify the API. The _.map method now provides the same functionality as _.pluck by allowing you to extract a specific property from each object in a collection.
How to Achieve the Same Result with _.map? We can achieve the same result as _.pluck using _.map by specifying a function to access the desired property.
Syntax:_.map(collection, [iteratee=_.identity]) Example: This example shows the use of _.map() function.
JavaScript
const _ = require("lodash")
const people = [
{ name: 'John', age: 30 },
{ name: 'Jane', age: 25 },
{ name: 'Jack', age: 35 }
];
// Using _.map to get an array of names
const names = _.map(people, 'name');
console.log(names);
Output:
[ 'John', 'Jane', 'Jack' ] ConclusionThe deprecation of Lodash’s _.pluck in favor of _.map with a property accessor reflects an evolution towards a more versatile and consistent approach for handling data transformation in JavaScript. By using _.map , developers can achieve the same functionality as _.pluck while benefiting from a method that offers greater flexibility and integration with other Lodash functionalities.
|