これはbabel / ES7の質問です(redux reducerの使用について)
一部のプロパティのみ「段」を更新したい。不変性の心で好ましい方法は何ですか?
TRY 1 と TRY 3 のみが正しくマージ/更新されるようです。
両者に違いはありますか?私にとってはTRY 3が最短なので(TRY 1に違いがない場合)
ありがとう
const people = { byID: {
gaston : { name:'Gaston', age: 22 },
dan : { name: 'gaston', age: 44 }
}
}
const currentID = "dan"
///
// TRY 1
const thisID = {}
thisID[currentID] = {...people.byID[currentID],
age: 20,
sex: 'male',
}
const newPeople = {...people,
byID: {...people.byID,
...thisID
}
}
console.log( newPeople ) // OK
//
// TRY 2
const newPeople2 = {}
newPeople2.byID = {}
newPeople2.byID[currentID] = {}
newPeople2.byID[currentID]["age"] = 20
newPeople2.byID[currentID]["sex"] = "male"
const newPeople3 = {...people, ...newPeople2}
console.log( newPeople3 ) // NOPE (not merge)
//
// TRY 3
const newPeople4 = {...people}
newPeople4.byID = newPeople4.byID || {}
newPeople4.byID[currentID] = newPeople4.byID[currentID] || {}
newPeople4.byID[currentID]["age"] = 20
newPeople4.byID[currentID]["sex"] = "male"
console.log(newPeople4) // OK
ここに出力があります
TRY 1
{"byID":{"gaston":{"name":"Gaston","age":22},"dan":{"name":"gaston","age":20,"sex":"male"}}}
TRY 2
{"byID":{"dan":{"age":20,"sex":"male"}}}
TRY 3
{"byID":{"gaston":{"name":"Gaston","age":22},"dan":{"name":"gaston","age":20,"sex":"male"}}}