Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove data from nested objects without mutating

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.

like image 623
Daniel Storch Avatar asked Feb 11 '16 14:02

Daniel Storch


1 Answers

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
like image 159
Dan Abramov Avatar answered Sep 25 '22 17:09

Dan Abramov