Last active
February 1, 2019 03:33
-
-
Save Dindaleon/f71e521e5095a674a0df8762eb0fc376 to your computer and use it in GitHub Desktop.
How to remove an item from object without mutating it
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 | |
// Source: http://stackoverflow.com/questions/35342355/remove-data-from-nested-objects-without-mutating | |
// We can also do the following if we have more nested items: | |
const { | |
[queueName]: { | |
[id]: {}, | |
...others | |
} | |
} = state; | |
return others; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment