trstephen
trstephen

Reputation: 33

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

I'd like to use lodash to selectively mutate properties in an object.

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 }

Is it possible to achieve this using the kind of composition I've outlined above or should I stick to something like

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

Upvotes: 3

Views: 1992

Answers (1)

dmlittle
dmlittle

Reputation: 999

You are looking for _.mapValues and _.protoype.value as andlrc pointed out. You'll end up creating a new object with the new values and merge it with the original one :

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;
}

Upvotes: 5

Related Questions