我正在Redux中具有规范化状态的应用程序上工作。我的一个实体是另一个的“父”实体,因此,当我删除该父实体时,我想删除与该父实体关联的所有子实体。
为了删除单个实体(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
开头的键。
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);