具有多个更改的传播属性:单行 ecma 不变性

spread properties with multiple changes: one-liner ecma immutability

我刚刚更改了这个

const newCities = {...newState.cities};
newCities[action.payload.id] = action.payload;
newState.cities = newCities;

单线

newState.cities = {...newState.cities, [action.payload.id]: action.payload};

但是我该如何改变这个

const newCities = {...newState.cities};
action.payload.forEach(city=> newCities[city.id] = city);
newState.cities = newCities;

到单线?东西~=

newState.cities = {...newState.cities, action.payload.map(city=> [city.id]: city)};

最终解:

newState.cities = {...newState.cities, ...action.payload.reduce((o,a)=> ({...o,[a.id]:a}),{})};

之前忘记初始化reduce数组=)

旧方法: 可能是这样?

newState.cities = {...newState.cities, ...action.payload.map(city=> ({[city.id]: city}) )};

更新:

newState.cities = {...newState.cities, ...action.payload.reduce(city=> ({[city.id]:city}) )};

更新(完全丑陋):

newState.cities = {...newState.cities, ...action.payload.map((o)=> ({[o.id]:o}) ).reduce((o,a)=>({...o,...a}))};