Reputation: 337
I try to delete an dynamic property of an object. The problem is that the property is depending of an array of keys. Lets see the code :
let keys = ['23', 'test', '12']; // Example but this is dynamic
let temp = this.array;
keys.forEach(k => {
temp = temp[k];
});
delete temp;
I want to delete this.array['23']['test']['12']. But I got an error : 'delete cannot be called on an identifier in strict mode'. How to do that ?
Upvotes: 1
Views: 1520
Reputation: 14679
I want to delete this.array['23']['test']['12']
Writing just that, delete this.array['23']['test']['12']
, will work. But with your syntax, delete temp
, you aren't deleting a property, you're trying to delete a variable. That won't fly. Even in the non-strict mode it won't alter the this.array
object, you'd be simply declaring a variable and undeclaring it.
With your loop, you should stop one step earlier to delete a property, not a variable:
keys.forEach((key, index, arr) => {
if (index < arr.length - 1) {
temp = temp[key];
} else {
delete temp[key];
}
});
Upvotes: 4
Reputation: 360
You may not be able to delete it but you can set it to null
. Try:
temp = null;
Upvotes: 0