2017-02-23 6 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

さてあなたもES6で、このためlodashは必要ありません。

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

を変異させたくない場合私はロダシュが初心者の方が良いと思うので、蒸散に対処する必要はありません。 – bcherny

1

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

関連する問題