Skip to content

Instantly share code, notes, and snippets.

@toklok
Forked from Dindaleon/removeItemFromObject.js
Created February 1, 2019 03:33
Show Gist options
  • Save toklok/e464e62aa4b016194c35424ba0aa9b7b to your computer and use it in GitHub Desktop.
Save toklok/e464e62aa4b016194c35424ba0aa9b7b to your computer and use it in GitHub Desktop.
How to remove an item from object without mutating it
// 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