从不可变对象中删除键(redux 状态)

Delete key from immutable object (redux state)

我正在编写一个 redux reducer 来从状态对象中删除一个键:

state = {
  items: {
    key1: {foo: 'bar'},
    key2: {foo: 'baz'}
  },
  someOtherKey: 'value'
}

我的减速器:

function reducer(state, action) {
  if (action=='DEL') {
    return {
      ...state,
      items: {
        ...state.items,
        [action.key]: undefined
      }
    }
  }
}       

我预计这会 return 一个新状态,其中相应的 属性 被删除,但它 return 是一个新状态,密钥仍然存在于对象中但具有值 undefined.

在ES6中有没有一种优雅的方式来编写这样的reducer?我想我可以使用 Object.assign 并删除 属性,但是上面的模式更具表现力,所以如果可能的话我想这样写。

我最终使用了 lodash 函数 omit:

import { omit } from 'lodash'

function reducer(state, action) {
  if (action=='DEL') {
    return {
      ...state,
      items: omit(state.items, action.key)
      }
    }
  }
}

lodash 库包含这样一个函数的事实让我假设可能没有更简单的方法来简单地表达操作 JavaScript。如果我错了,请告诉我;我很想听听。

未经测试,这个怎么样?它将为每个项目创建一个浅拷贝(不可变的),除了你不关心的那个。

function reducer(state, action) {
    if (action == 'DEL') {
        return {
            ...state,
            items: Object.keys(state.items).reduce((obj, key) => {
                if (key !== action.key) {
                    obj[key] = { ...state.items[key]
                    }
                }
            }, {})
        }
    }
}

另一种技术:复制对象然后删除键:

function reducer(state, action) {
  if (action=='DEL') {
    let newItems = {...state.items};  // Copy the object
    delete newItems[action.key];      // Remove key from the copy
    return {
      ...state,
      items: newItems,
    };
  }
}