使用 lodash 将函数应用于对象的过滤属性

Use lodash to apply a function to filtered properties of an object

我想使用 lodash 有选择地改变对象中的属性。

var foo = { 'a': 1, 'b': 2, 'c': 3 };

function addOne(num) {
    return num + 1;
}

var propsToTransform = ['a', 'b'];

_(foo).pick(propsToTransfrom)
  .map(addOne);

// I want foo = { 'a': 2, 'b':3, 'c':3 }

是否可以使用我上面概述的那种构图来实现这一点,或者我应该坚持使用

_.forEach(propsToTransform, (prop) => {
  if (foo[prop]) {
    foo[prop] = addOne(foo[prop]);
  }
});

正如 andlrc 指出的那样,您正在寻找 _.mapValues and _.protoype.value。您最终将使用新值创建一个新对象并将其与原始对象合并:

var foo = { 'a': 1, 'b': 2, 'c': 3 };
var propsToTransfrom = ['a', 'b']

// Create a new object with the new, modified values and merge it onto the original one
var bar = _.merge(foo, _(foo).pick(propsToTransfrom).mapValues(addOne).value());

console.log(bar); // { 'a': 2, 'b': 3, 'c': 3 }

function addOne(num) {
    return num + 1;
}