babeljs - What's the difference and/or preferred way of updating a deep property? -
this babel/es7 question (for redux reducer use)
i want update "dan" in properties. what's preferred way immutability mind?
it seems try 1 , try 3 merge/update correctly.
is there difference between two? me try 3 wins because it's shortest (if no difference between try 1)
thanks
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
here outputs
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"}}}
using spread operator, can do:
const updatedpeople = { byid: { ...people.byid, dan: { ...people.byid.dan, age: 20, sex: "male" } } };
if need id dynamic, using computed property keys (an other es6 feature, part of destructuring):
const id = 'dan'; const updatedpeople = { byid: { ...people.byid, [id]: { ...people.byid[id], age: 20, sex: "male" } } };
those solutions immutability full proof, though, if you're not familiar es6 syntax, can hard read , if have more complex data, might consider using immutablejs (or kind of immutable library)
Comments
Post a Comment