2017-02-23 42 views
1

有沒有辦法更新對象數組內對象中的單個字段?用Javascript/Lodash更新對象數組中單個字段的對象

PeopleList= [ 
    {id:1, name:"Mary", active:false}, 
    {id:2, name:"John", active:false}, 
    {id:3, name:"Ben", active:true}] 

例如,將John的活動設置爲true。

我試圖在Lodash中做到這一點,但它沒有返回正確的結果。它返回一個lodash包裝。

 updatedList = _.chain(PeopleList) 
     .find({name:"John"}) 
     .merge({active: true}); 

回答

2

那麼你甚至不需要lodash這與ES6:

PeopleList.find(people => people.name === "John").active = true; 
//if the record might not exist, then 
const john = PeopleList.find(people => people.name === "John") 
if(john){ 
    john.active = true; 
} 

或者,如果你不想變異原始列表

const newList = PeopleList.map(people => { 
    if(people.name === "John") { 
    return {...people, active: true}; 
    } 
    return {...people}; 
}); 
+0

我認爲Lodash對初學者來說更好,所以他們不必處理轉譯。 – bcherny

1

_.find(PeopleList, { name: 'John' }).active = true