Skip to content

Instantly share code, notes, and snippets.

@Dindaleon
Last active February 1, 2019 03:33
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Dindaleon/f71e521e5095a674a0df8762eb0fc376 to your computer and use it in GitHub Desktop.
Save Dindaleon/f71e521e5095a674a0df8762eb0fc376 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