Daniel Storch Daniel Storch - 12 days ago 6
Javascript Question

Remove data from nested objects without mutating

Is there any elegant way of removing and 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 a ID and another array with objects, like this:

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


I receive both the ID's and need to remove the item with id abc.

Answer

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
Comments