2017-11-10 168 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);