![](/img/trans.png)
[英]Lodash uniqWith comparator function modify object properties
[英]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]);
}
});
您正在尋找_.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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.