2017-11-10 103 views
4

所以基本上,我有一个对象数组,我只想更新数组中满足条件的对象。我想知道是否有像解决这个问题的功能良好的方法。现在我正在使用lodash。下面是和示例:有没有lodash函数或'lodash方式'来做一个条件_.map?

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"}]; 

回答

1

可以使用Array#map(或Lodash的等同物),如果该类型是将创建一个新的更新对象三元a使用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);

4

这里没有必要使用map方法。

您可以使用简单的forEach函数,将回调函数传递给它。

var results = _.forEach(things, function (thing) { 
    if(thing.type === "a") { 
    thing.value = "500"; 
    } 
}); 
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; }

0

这或许有点早,但与proposal for object rest spread这是目前在阶段3,你可以解决这个问题是这样的:

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