Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reset object to empty object keeping references intact in non-linear time

Tags:

javascript

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?

like image 394
Wex Avatar asked Oct 20 '25 05:10

Wex


1 Answers

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).

like image 63
jcaron Avatar answered Oct 22 '25 21:10

jcaron