What happened to Lodash _.pluck?

JavascriptLodash

Javascript Problem Overview


I once used Lodash _.pluck...I loved pluck...

Realizing Lodash no longer supports pluck (as of Lodash 4.x), I'm struggling to remember what to use instead...

I went to the docs, hit cmd-f, typed 'pluck', but my poor abandoned friend is not even given a proper mention...not even a 'has been replaced by'...

Can someone please remind me what I'm supposed to use instead?

Javascript Solutions


Solution 1 - Javascript

Ah-ha! The Lodash Changelog says it all...

"Removed _.pluck in favor of _.map with iteratee shorthand"

var objects = [{ 'a': 1 }, { 'a': 2 }];

// in 3.10.1
_.pluck(objects, 'a'); // → [1, 2]
_.map(objects, 'a'); // → [1, 2]

// in 4.0.0
_.map(objects, 'a'); // → [1, 2]

Solution 2 - Javascript

There isn't a need for _.map or _.pluck since ES6 has taken off.

Here's an alternative using ES6 JavaScript:

clips.map(clip => clip.id)

Solution 3 - Javascript

Use _.map instead of _.pluck. In the latest version the _.pluck has been removed.

Solution 4 - Javascript

If you really want _.pluck support back, you can use a mixin:

const _ = require("lodash")

_.mixin({
    pluck: _.map
})

Because map now supports a string (the "iterator") as an argument instead of a function.

Solution 5 - Javascript

For plucking single or multiple properties:

_.mixin({
    properties: (paths) =>
            (obj) => paths.reduce((memo, path) => [...memo, obj[path]], []),
    pluck: (obj, ...keys) => _.map(obj, _.flatten(keys).length > 1
                                    ? _.properties(_.flatten(keys))
                                    : (o) => o[keys[0]])
})
var stooges = [{name: 'moe', age: 40}, {name: 'larry', age: 50}, {name: 'curly', age: 60}];

// underscore compatible usage
_.pluck(stooges, 'name');
=> ["moe", "larry", "curly"]

// multiple property usage
_.pluck(stooges, 'name', 'age')
=> [["moe",40], ["larry",50], ["curly",60]]

// alternate usage
_.pluck(stooges, ['name', 'age']) 
=> [["moe",40], ["larry",50], ["curly",60]]

Solution 6 - Javascript

Or try pure ES6 nonlodash method like this

const reducer = (array, object) => {
  array.push(object.a)
  return array
}

var objects = [{ 'a': 1 }, { 'a': 2 }];
objects.reduce(reducer, [])

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsfletcheView Question on Stackoverflow
Solution 1 - JavascriptsfletcheView Answer on Stackoverflow
Solution 2 - JavascriptMichael J. CalkinsView Answer on Stackoverflow
Solution 3 - JavascriptDheeraj NalawadeView Answer on Stackoverflow
Solution 4 - JavascriptRichie BendallView Answer on Stackoverflow
Solution 5 - JavascriptOrwellophileView Answer on Stackoverflow
Solution 6 - JavascriptPayteRView Answer on Stackoverflow