I'm using TypeScript along with TSLint, and I have the following code:
var myObj = {}
var id = "key"
myObj[id] = 1
delete myObj[id]
But I receive a hint from TSLint: Do not delete dynamically computed property keys. (no-dynamic-delete)
The rationale for this rule (as stated on the documentation for TSLint):
Deleting dynamically computed keys is dangerous and not well optimized.
My question is, without disabling this hint in the TSLint configuration file, how should I safely and optimally delete the id
key in myObj
?
Use delete to Remove Object Keys The special JavaScript keyword delete is used to remove object keys (also called object properties). While you might think setting an object key equal to undefined would delete it, since undefined is the value that object keys that have not yet been set have, the key would still exist.
The delete operator deletes both the value of the property and the property itself. After deletion, the property cannot be used before it is added back again. The delete operator is designed to be used on object properties. It has no effect on variables or functions.
The _. omit function takes your object and an array of keys that you want to remove and returns a new object with all the properties of the original object except those mentioned in the array. This is a neat way of removing keys as using this you get a new object and the original object remains untouched.
delete keyword is used to delete properties of an object in javaScript.
a) ignore the warning
b) use a Map
instead
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With