Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Statically delete object key JavaScript

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?

like image 382
Ari Seyhun Avatar asked Feb 18 '18 13:02

Ari Seyhun


People also ask

How do I remove a key from a JavaScript object?

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.

How do we delete the object property in JavaScript?

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.

How do I remove all objects from a key?

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.

Which keyword is used for deleting properties on objects?

delete keyword is used to delete properties of an object in javaScript.


1 Answers

a) ignore the warning
b) use a Map instead

like image 158
Bergi Avatar answered Sep 21 '22 00:09

Bergi