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"}];
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"}];
Share
asked Nov 10, 2017 at 22:13
LynchburgExplorerLynchburgExplorer
7208 silver badges9 bronze badges
4 Answers
Reset to default 4There 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";
}
});
You could just map the new objects with a condition inside of Object.assign
, without mutating 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; }
You can use Array#map (or Lodash's equivalent) with a ternary that will create a new updated object if the type is a
using Object#assign:
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);
This is perhaps a little early, but with the proposal for object rest spread which is currently in stage-3 you could 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);
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745055535a4608643.html
评论列表(0条)