Here is my reducer body code fragment:
const newState = {
...state,
programs: {
...state.programs,
...Object.assign(
{},
...action.payload.map(
(channelName) =>
({
[channelName]: {
...state.programs[channelName],
selected: true
}
})
)
)
}
}
return newState
Is there any chance to get rid of Object.assign
in this case?
The classical advice to change Object.assign({}, a)
to { ...a }
does not work in this case, because here we already have ...action.payload.map
, so it would result in ... { ...a }
which makes spread to produce array-like keys of 0,1,2...
Is there any elegant way to transform my code correctly?
Another option to use Object.fromEntries
:
const action = {
payload: ['discoveryChannel']
}
const state = {
programs: {
cartoonNetwork: {
description: '',
when: new Date()
},
discoveryChannel: {
description: '',
when: new Date()
}
}
}
const newState = {
...state,
programs: {
...state.programs,
...Object.fromEntries(
action.payload.map(
channelName => ([
channelName, {...state.programs[channelName], selected: true}
])
)
)
}
}
console.log(newState);