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"}];
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";
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With