Let's say I have obj1
with only enumerable properties:
var obj1 = { a: 1, b: 2, c: 3 };
I then create obj2
which holds a reference to obj1
:
var obj2 = obj1;
obj1 === obj2; // true
At some point, I want to reset obj1
to an empty object:
for (key in obj1) {
delete obj1[key];
}
obj1 === obj2; // true
But I'd like to avoid having to iterater over all the properties:
obj1 = {};
obj1 === obj2; // false (this obviously doesn't work)
Is there another solution?
If you have flexibility on the data model, then store the actual properties in a child object:
var obj1 = {theData: { a: 1, b: 2, c: 3} };
then you can reset the properties with obj1.theData = {}
.
Of course, that implies that access to any property will incur an additional "hop", so depending on how often you access the data (read or write it) vs. reset the object, you might be better off keeping the delete
loop.
Other than that, I don't believe you can reset an object like you can an Array (via a.length=0
).
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