克隆 JavaScript 对象时如何排除键列表?

How do I exclude a list of keys when cloning a JavaScript object?

我正在开发一个在 Redux 中具有规范化状态的应用程序。我的一个实体是另一个实体的 'parent' 实体,因此当我删除该父实体时,我想删除与该父实体关联的所有子实体。

对于删除单个实体(1个ID),我一直在使用这种模式:

// ../reducers/entity.js
case DELETE_ENTITY: {
    const entityId = action.payload.entityId;
    const {[entityId]: ignore, ...stateWithoutEntity} = state;
    return stateWithoutEntity;
}

对于上下文,上面代码段中的 state 的形状如下:

{
    ID_1: {
        //entity 1 value
    },
    ID_2: {
        //entity 2 value
    },
    // etc...
}

是否有类似的删除多个实体列表(n个ID)的模式?

换句话说,是否存在克隆 JavaScript 对象同时排除多个键的模式?

// ../reducers/entity.js
case DELETE_PARENT_ENTITY: {
    const parentId = action.payload.parentId;
    const childrenIdsToRemove = action.payload.children;
    // How do I clone the state while excluding each ID in childrenIdsToRemove?
}

如果您有很多要删除的对象的键,您可以使用 Object.entries 然后 filter,最后 reduce 来创建最终对象。

下面是一个简单的示例,基本上删除了所有以 entity 开头的键。

Update, Thanks to comments changed to fromEntries instead of reduce

const x = {
  'entity1': 1,
  'something': 2,
  'entity2': 3,
  'another': 4
}


const y =
  Object.fromEntries(Object.entries(x)
  .filter(([k]) => !/^entity/.test(k)));
  
console.log(y);