How do I remove a key from a JavaScript object?
Here's your "magic spell" for banishing a key from a JavaScript object: the trusty delete
operator:
The delete
wizardry whisks away the property altogether, so it conveniently ghosts you to undefined
if you dare to call it afterward.
Removing dynamic keys
If your key name is something mysterious that's stored in a variable or you need your crystal ball to calculate it, []
bracket notation is the way to go:
You'll find this trick especially crafty in functions when you need to perform some dark arts on objects based on changing conditions.
Preventing unintended obliteration
Before casting your delete
incantation, it's highly recommended to confirm that your object is indeed haboring the property you're targeting. Else, you may end up with some unwelcome side effects:
Using good old hasOwnProperty
makes sure you're not trying to excise properties from the object's ancestry line.
Alternatives to waving the delete
wand
If you're someone who likes to keep things intact or work somewhere delete
is frowned upon (React says "Hi!"), you might find these alternatives to your liking:
Conjuring a new object with the object spread and destructuring
This approach creates a duplicate of your original, minus the key in question. No mutations here!
Calling upon the spirits of functional libraries
The Lodash's _.omit
function is a neat trick:
Cooking up a new object via reduce
This magical method uses old man reduce
to round up all the keys that didn't cross paths with 'delete' into a shiny new object.
Resistance against deletion
Certain keys might be possesed by the configurable
attribute set to false
, and may strike back when you try to delete
them:
Conduct a post-mortem with Object.getOwnPropertyDescriptor
to understand these paranormal activities.
When possession is better than exorcism
Sometimes, it's better to exile a property rather than eradicate it:
The key continues to haunt the object, but its value is as desolate as undefined
. This practice maintains the spooky shape of the object, which might be handy in specific necromancy-like data transformations.
Was this article helpful?