Skip to content

Instantly share code, notes, and snippets.

@jwrigh26
Last active June 3, 2021 22:06
Show Gist options
  • Save jwrigh26/05dabf19cb69868becf7677bb384b3bc to your computer and use it in GitHub Desktop.
Save jwrigh26/05dabf19cb69868becf7677bb384b3bc to your computer and use it in GitHub Desktop.
Remove Object Properties with Destructing
// Helper method to delete without mutating
// Why not use delete? It's a mutable operation (side-effects).
// By using object destructuring, we have a one-liner approach.
// Inspired by: https://ultimatecourses.com/blog/remove-object-properties-destructuring
const removeItem = (key, { [key]: _, ...obj }) => obj;
// How does this work?
// We pass in the name of the key we wish to remove from the object.
// For the second param, we pass in the object
// However the method itself, destructures the object by
// taking the key and by wrapping it in brackets it
// dynamically creates a new variable and assings it "blank"
// If we wanted to reference the deleted value we could provide
// a name instead of "_".
// However for our purpose we don't wish to refer back so we pass blank.
// the fn then just returns the obj. However, the object now excludes
// the key in question because the rest protocol gives us everything
// left over via destructring.
// Example
/*
const foo = {
herp: 'Herp',
derp: 'Derp',
}
const boo = removeItem('herp', foo);
console.log('Boo:');
console.log(boo);
console.log('Foo:');
console.log(foo);
// output
// Boo:
// { derp: "Derp" }
// Foo:
// { herp: "Herp", derp: "Derp" }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment