我曾经用过Lodash…我喜欢采摘……

意识到Lodash不再支持pluck(从Lodash 4.x开始),我努力记住用什么来代替…

我去看医生,点击cmd-f,输入“pluck”,但我可怜的被遗弃的朋友甚至没有得到适当的提及……甚至没有一个'has been replace by'…

谁能提醒我该用什么代替?


啊哈!Lodash更新日志说明了一切…

“删除_。支持……带有迭代对象简写的映射”

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]

使用_。Map而不是_.pluck。在最新版本中,_。拔毛已被移除。

没有必要。地图或_。自ES6起飞以来,我们一直在努力。

下面是一个使用ES6 JavaScript的替代方案:

剪辑。Map (clip => clip.id)

或者尝试像这样的纯ES6 nonlodash方法

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

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

如果你真的想_。拔下支持,你可以使用mixin:

const _ = require("lodash")

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

因为map现在支持字符串(“迭代器”)作为参数,而不是函数。

用于提取单个或多个属性:

_.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]]