是否有lodash函数或“lodash方式”来执行条件_.map?

时间:2017-11-10 22:13:10

标签: javascript dictionary functional-programming lodash

所以基本上,我有一个对象数组,我想只更新数组中满足条件的对象。我想知道是否有一个很好的功能方法来解决这个问题。现在我正在使用lodash。以下是示例:

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 个答案:

答案 0 :(得分:4)

此处无需使用map方法。

您可以通过向其传递回调功能来使用简单的forEach功能。

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

答案 1 :(得分:2)

您可以使用Object.assign内的条件映射新对象,而不会改变原始对象。



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 :(得分:1)

如果类型a使用Array#map,您可以使用Object#assign(或Lodash等效的)三元组创建新的更新对象:



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




答案 3 :(得分:0)

这可能有点早,但目前处于第3阶段的proposal for object rest spread你可以这样解决:

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