Jeanluca Scaljeri
Jeanluca Scaljeri

Reputation: 29149

How to remove all elements from hash and keep the reference

I need to remove everything from a hash/object and keep the reference. Here is an example

var x = { items: { a: 1, b: 2} }

removeItems(x.items) ;
console.log(x.items.clean) ;

function removeItems(items) {
    var i ;
    for( i in items; i++ ) {
       delete items[i] ;
    }

    items.clean = true ;
}

I was wondering if there is a shorter way to achieve this. For example, cleaning an array can be done as follows

myArray.length = 0 ;

Any suggestions?

Upvotes: 4

Views: 1798

Answers (3)

Bergi
Bergi

Reputation: 664936

This does not work:

var i ;
for( i in items; i++; ) {
   delete items[i] ;
}

It creates a for-loop with the init code i in items (which btw evaluates to false as there is no "undefined" key in items, but that doesn't matter), and the condition i++ and no update code. Yet i++ evaluates to the falsy NaN, so your loop will immediately break. And without the second semicolon, it even as a SyntaxError.

Instead, you want a for-in-loop:

for (var i in items) {
    delete items[i];
}

Btw, items.clean = true; would create a new property again so the object won't really be "clean" :-)

I was wondering if there is a shorter way to achieve this. For example, cleaning an array can be done as follows

No. You have to loop all properties and delete them.

Upvotes: 1

loganfsmyth
loganfsmyth

Reputation: 161517

There isn't a shorter way, sorry. Your loop shouldn't have the i++ though.

function removeItems(items) {
  for(var i in items) {
    delete items[i];
  }

  items.clean = true;
}

Restructuring your code and just doing x.items = {} would be better though.

Upvotes: 0

Benjamin Gruenbaum
Benjamin Gruenbaum

Reputation: 276406

There is no easy way to do this at the moment, however the ECMAScript committee sees this need and it is in the current specification for the next version of JS.

Here is an alternative solution, using ECMAScript 6 maps:

var x = {}
x.items = new Map();
x.items.set("a",1);
x.items.set("b",2);

//when you want to remove all the items

x.items.clear();

Here is a shim for it so you can use it in current-day browsers.

Upvotes: 8

Related Questions