javascript - spread properties with multiple changes: one-liner ecma immutability -
i changed
const newcities = {...newstate.cities}; newcities[action.payload.id] = action.payload; newstate.cities = newcities;
to one-liner
newstate.cities = {...newstate.cities, [action.payload.id]: action.payload};
but how change this
const newcities = {...newstate.cities}; action.payload.foreach(city=> newcities[city.id] = city); newstate.cities = newcities;
to one-liner? ~=
newstate.cities = {...newstate.cities, action.payload.map(city=> [city.id]: city)};
final solution:
newstate.cities = {...newstate.cities, ...action.payload.reduce((o,a)=> ({...o,[a.id]:a}),{})};
previously forgot initialize reduce array =)
old approaches: may way?
newstate.cities = {...newstate.cities, ...action.payload.map(city=> ({[city.id]: city}) )};
updated:
newstate.cities = {...newstate.cities, ...action.payload.reduce(city=> ({[city.id]:city}) )};
update (complete ugliness):
newstate.cities = {...newstate.cities, ...action.payload.map((o)=> ({[o.id]:o}) ).reduce((o,a)=>({...o,...a}))};
Comments
Post a Comment