Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove all elements from hash and keep the reference

Tags:

javascript

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?

like image 736
Jeanluca Scaljeri Avatar asked Jan 14 '23 20:01

Jeanluca Scaljeri


2 Answers

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.

like image 151
Benjamin Gruenbaum Avatar answered Jan 19 '23 10:01

Benjamin Gruenbaum


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.

like image 30
Bergi Avatar answered Jan 19 '23 10:01

Bergi