3

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?

Wex
  • 15,539
  • 10
  • 64
  • 107
  • Almost a dupe of [How to quickly clear a Javascript Object?](http://stackoverflow.com/questions/684575/how-to-quickly-clear-a-javascript-object) – p.s.w.g Aug 16 '14 at 01:41
  • Yeah, but the constraint that I retain reference is important here. – Wex Aug 16 '14 at 01:44
  • 2
    You can keep the delete code short using: `Object.keys(obj).forEach(function(key){delete obj[key]})`. This deletes only enumerable, deletable properties. A for..in loop must include a *hasOwnProperty* test. – RobG Aug 16 '14 at 01:52
  • 1
    Create a helper function and do `empty(obj1);`. – Felix Kling Aug 16 '14 at 02:04

1 Answers1

5

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

jcaron
  • 17,302
  • 6
  • 32
  • 46
  • 3
    Noting that setting an array's length to zero only deletes numeric properties, it doesn't delete others. ;-) – RobG Aug 16 '14 at 01:54