我想使用 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]);
}
});
最佳答案
您正在寻找_.mapValues
和 _.protoype.value
正如andlrc指出的那样。您最终将创建一个具有新值的新对象并将其与原始对象合并:
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;
}
关于javascript - 使用 lodash 将函数应用于对象的过滤属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37447815/