【问题标题】:How do I exclude a list of keys when cloning a JavaScript object? [duplicate]克隆 JavaScript 对象时如何排除键列表? [复制]
【发布时间】:2020-09-28 20:08:32
【问题描述】:

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

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

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

对于上下文,上述 sn-p 中的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 你可以创建任何你想要的过滤逻辑。
  • 您可能想查看this one

标签: javascript redux immutability


【解决方案1】:

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

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

更新,感谢 cmets 改为 fromEntries 而不是 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);

【讨论】:

  • Object.fromEntries.reduce 的惯用版本
  • @Thankyou Nice!,更新使用..
  • 最终使用了这个表格 - 谢谢 Keith!
猜你喜欢
  • 2011-04-15
  • 1970-01-01
  • 2011-03-29
  • 2015-01-08
  • 2016-04-14
  • 2013-04-06
  • 2011-10-17
  • 2017-05-22
相关资源
最近更新 更多