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

Basically, I have an array of objects, and I would like to update only the objects in the array that satisfy the condition. I want to know if there is a good functional way to solve this problem. I'm using lodash right now. Here is an 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"}];
+4
source share
4 answers

There is no need to use the method map.

You can use just a function forEachby passing it a callback function .

var results = _.forEach(things, function (thing) { 
  if(thing.type === "a") {
    thing.value = "500";
  } 
});
+4
source

You can simply map the new objects to the condition inside Object.assignwithout changing the original object.

var things = [{ id: 1, type: "a", value: "100" }, { id: 2, type: "b", value: "300" }, { id: 3, type: "a", value: "100" }],
    results = things.map(o => Object.assign({}, o, o.type === "a" && { value: 500 }));

console.log(results);
.as-console-wrapper { max-height: 100% !important; top: 0; }
+2

Array # map ( Lodash) , , a #:

var things = [
    {id: 1, type: "a", value: "100"}, 
    {id: 2, type: "b", value: "300"}, 
    {id: 3, type: "a", value: "100"}
];
var result = things.map(function (thing) { 
    return thing.type === 'a' ? Object.assign({}, thing, { value: 500 }) : thing;
});

console.log(result);
+1
source

Perhaps this is a little earlier, but with a proposal to place the remainder of the object , which is currently at stage 3, you can solve it like this:

const things = [
    {id: 1, type: "a", value: "100"}, 
    {id: 2, type: "b", value: "300"}, 
    {id: 3, type: "a", value: "100"},
];
const result = things.map(e => e.type === 'a' ? {...e, value: 500 } : e);
console.log(result);
Run code
0
source

Source: https://habr.com/ru/post/1689092/


All Articles