Created
December 18, 2020 20:52
-
-
Save DoctorDerek/1216d8029d456537d6cb154d8b205ce5 to your computer and use it in GitHub Desktop.
How to Remove a Key from an Object in JavaScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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