使用 Lodash 对对象的过滤属性应用函数。

3
我想使用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]);
  }
});
1个回答

5
你正在寻找和lrc指出的一样的 _.mapValues_.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;
}

这是一个很好的解决方案。您可以更加勇敢并省略 bar。它缩短为 _.merge(foo, _(foo).pick .... );,因为 merge 将改变 foo。@dmlittle 如果您能将 console.log 的输出设置为 { 'a': 2, 'b': 3, 'c': 3 },我可以标记为已接受。 - trstephen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接