Search code examples
javascriptreactjsreduxreact-redux

How to delete an item from my Reducer Object?


I have an object in my reducer like this :

clientData : {
1080 : [{ID : 1111,name : 'John'},{ID : 2222,name : 'Stan'},],
1090 : [{ID : 3333,name : 'Adam'},{ID : 4444,name : 'Alan'},]
}

And I want to be able to delete an item (for example Stan with 2222 ID's) The problem that is I don't have the key of my property (1080), and I don't have any idea how to achieve it. I've tried the Object.values(object1) but it convert my object to array and I lost all my architecture. Have you an idea please ?


Solution

  • Removing from existing objects might not be good, you can use Object.entries and filter to remove id.

    If you want to change existing pass data to reducer

    const data = {
      1080: [
        { ID: 1111, name: "John" },
        { ID: 2222, name: "Stan" },
      ],
      1090: [
        { ID: 3333, name: "Adam" },
        { ID: 4444, name: "Alan" },
      ],
    };
    
    const remove = (id, data) => {
      const entries = Object.entries(data);
      return entries.reduce((acc, [key, value]) => {
        const newValue = value.filter((item) => item.ID !== id);
        acc[key] = newValue;
        return acc;
        // return { ...acc, [key]: newValue };
      }, {}); // for updating existing data here
    };
    
    
    console.log(remove(2222, data))