Javascript 映射对象,转换为数组,然后再转换回对象

Javascript 映射对象,转换为数组,然后再转换回对象,javascript,redux,Javascript,Redux,我在redux reducer中使用了以下代码: case 'REMOVE_FL_EVENT' : return{ ...state, events: Object.keys(state.events).map(group => { return state.events[group].filter(item => item.id !== action.id) }) } 这里发生的是state.events是

我在redux reducer中使用了以下代码:

  case 'REMOVE_FL_EVENT' : 
    return{
      ...state,
      events: Object.keys(state.events).map(group => {
        return state.events[group].filter(item => item.id !== action.id)
      })
    }

这里发生的是state.events是一个对象,其中每个键都是它的事件组的名称,值是一个包含事件的数组。我要做的是,当我使用map将对象转换为数组时,如果发生了过滤器,请将其转换回原始状态,其中state.events不是数组,而是具有键原始名称的对象。

为此,可以使用map/reduce。首先将其映射,然后将其缩小为对象

case 'REMOVE_FL_EVENT' : 
  return{
    ...state,
    events: Object.keys(state.events).map(group => {
      return { [group]: state.events[group].filter(item => item.id !== action.id) }
    }).reduce((obj, event) => Object.assign(obj, event), {})
  }

输出将是一个以键为组的对象。让我知道它是否有效。

对于标准JS,您可以使用
reduce
将数组转换回obj:

arr.reduce((acc,o)=>Object.assign(acc,o),{})


使用
ramda.js
可以过滤对象及其嵌套属性

无需使用
map
,您可以仅使用
reduce
,类似于:

 {
  ...state,
  events: Object.keys(state.events).reduce(
    (obj, event) => ({
      ...obj,
      [group]: state.events[group].filter(item => item.id !== action.id)
    }),
    {}
  )
})

更新
reduce
具有以下签名:

arr.reduce(回调[,initialValue])


因此,在我们的脚本中,我们给出了一个空对象作为累加的初始值。

reduce(event)的第二个参数在哪里起作用?这是必要的吗?我们为什么需要它?我的意思是,在什么情况下使用它?@DorLask如果我们没有建立初始值,那么
reduce
将使用数组中的第一个元素作为累加器。