双重传播问题 - 摆脱 Object.assign()

Double spread problem - getting rid of Object.assign()

这是我的 reducer 主体代码片段:

const newState = {
    ...state,
    programs: {
        ...state.programs,
        ...Object.assign(
            {},
            ...action.payload.map(
                (channelName) =>
                    ({
                        [channelName]: {
                            ...state.programs[channelName],
                            selected: true
                        }
                    })
            )
        )
    }            
}
return newState

在这种情况下是否有机会摆脱 Object.assign

Object.assign({}, a) 更改为 { ...a } 的经典建议在这种情况下不起作用,因为这里我们已经有 ...action.payload.map,所以它会导致 ... { ...a } make spread 生成类似数组的键 0,1,2...

有什么优雅的方法可以正确转换我的代码吗?

听说过reduce吗?

const action = {
  payload: ['discoveryChannel']
}

const state = {
  programs: {
    cartoonNetwork: {
      description: '',
      when: new Date()
    },
    discoveryChannel: {
      description: '',
      when: new Date()
    }
  }
}

const newState = {
  ...state,
  programs: {
    ...state.programs,
    ...action.payload.reduce(
      (acc, channelName) => {
        acc[channelName] = {
          ...state.programs[channelName],
          selected: true
        }

        return acc;
      }, {})
  }
}
console.log(newState);

另一个使用选项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);