Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save DoctorDerek/1216d8029d456537d6cb154d8b205ce5 to your computer and use it in GitHub Desktop.

Select an option

Save DoctorDerek/1216d8029d456537d6cb154d8b205ce5 to your computer and use it in GitHub Desktop.
How to Remove a Key from an Object in JavaScript
const myObject = { key: "🍫" }
myObject.key2 = "🍬"
myObject.key3 = "🍭"
console.log(delete myObject.key)
myObject.key2 = undefined
console.table(Object.entries(myObject))
// (index) key value
// 0 key2 undefined
// 1 key3 🍭
// Keys not on the object are undefined
console.log(myObject.key4) // undefined
// delete returns true for non-existent keys
console.log(delete myObject.key4) // true
console.log(myObject.key) // undefined
console.log(delete myObject.key) // true
// You can't delete variables, just keys
console.log(delete myObject) // false
// A non-configurable key is set using Object.defineProperty()
Object.defineProperty(myObject, "name", { configurable: false })
// Non-configurable keys can't be deleted by the delete keyword
console.log(delete myObject.name) // false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment