Remove data from nested objects without mutating

Daniel Storch picture Daniel Storch · Feb 11, 2016 · Viewed 9.3k times · Source

Is there any elegant way of removing an object from an array which is part of an array? I have been working with React and Redux for a while now but get stuck several hours everytime I have to remove or insert data without mutating the state.

The reducer is an array containing objects which have an ID and another array with objects, like this:

[
 { id:123,
   items:[
           { id: abc,
             name: albert
           }, 
           ... 
         ]
 }, 
 ... 
]

I receive both IDs and need to remove the item with ID abc.

Answer

Dan Abramov picture Dan Abramov · Feb 27, 2016

To remove an item from an array by id:

return state.filter(item => item.id !== action.id)

To remove a key from an object by id:

let copy = Object.assign({}, state) // assuming you use Object.assign() polyfill!
delete copy[action.id] // shallowly mutating a shallow copy is fine
return copy

(Bonus) The same with object spread operator proposal:

let { [action.id]: deletedItem, ...rest } = state
return rest