0

I am working on an app with a normalized state in Redux. One of my entities is the 'parent' entity of another, so when I delete that parent entity I want to delete all of the children entities associated with that parent.

For deleting a single entity (1 ID), I have been using this pattern:

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

For context, the state in the above snippet is shaped as such:

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

Is there a similar patten for deleting a list of multiple entities (n IDs)?

In other words, is there a pattern for cloning a JavaScript object while excluding several keys?

// ../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?
}

Jack Damon
  • 301
  • 1
  • 5
  • 15

1 Answers1

1

If you have lots of keys of an object you want to remove, you can use Object.entries and then filter, and then finally reduce to make the final object.

Below is a simple example, that basically remove all keys that start with 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);
Keith
  • 22,005
  • 2
  • 27
  • 44