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
.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With