Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a lodash function or a 'lodash way' to do a conditional _.map?

So basically, I have an array of objects and I'd like to update only the objects in the array that satisfy a condition. I want to know if there's like a good functional way of solving that problem. Right now I'm using lodash. Here's and example:

var things = [
    {id: 1, type: "a", value: "100"}, 
    {id: 2, type: "b", value: "300"}, 
    {id: 3, type: "a", value: "100"}
];
var results = _.map(things, function (thing) { 
    if(thing.type === "a") {
        thing.value = "500";
    } 
    return thing;
});
// => results should be [{id: 1, type: "a", value: "500"}, {id: 2, type: "b", value: "300"}, {id: 3, type: "a", value: "500"}];
like image 554
LynchburgExplorer Avatar asked Mar 08 '23 15:03

LynchburgExplorer


1 Answers

There is no need here to use map method.

You can use a simply forEach function by passing a callback function to it.

var results = _.forEach(things, function (thing) { 
  if(thing.type === "a") {
    thing.value = "500";
  } 
});
like image 82
Mihai Alexandru-Ionut Avatar answered Apr 30 '23 05:04

Mihai Alexandru-Ionut