Statically delete object key JavaScript
Asked Answered
T

1

9

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?

Thorite answered 18/2, 2018 at 13:44 Comment(5)
github.com/palantir/tslint/issues/3648Increate
Is it just suggesting you delete myObj.key without the []?Dramatist
@Dramatist no, delete myObj[id] is not the same as dekete myObj.id.Thorite
@AriSeyhun Please extend. Because afaik - it is exactly same (ommiting the mistypo).Parabolize
@DerZinger myObj[id] uses the variable id, not the field in the object with the key of id. For example let id = 'myKey'; myObj[id] this uses myObj.myKey but with a variable. But myObj.id doesn't use any variables for the key, only the id field directly.Thorite
J
6

a) ignore the warning
b) use a Map instead

Jewelljewelle answered 18/2, 2018 at 14:28 Comment(3)
Thanks, I went with mapsThorite
Did you just set myObj[id] to an empty string?Dermatoglyphics
@Dermatoglyphics Not sure I understand your question? No, deleting a property (what the OP wants) is different from setting it to an empty string.Jewelljewelle

© 2022 - 2024 — McMap. All rights reserved.