How to remove all items from the hash and save the link

I need to remove everything from the hash / object and save the link. 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 for this. For example, array cleaning can be done as follows

 myArray.length = 0 ; 

Any suggestions?

+4
source share
3 answers

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

Here is an alternative solution using ECMAScript 6 cards :

 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 the pad for it so you can use it in modern browsers.

+8
source

This does not work:

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

It creates a for-loop with the initialization code i in items (which btw evaluates to false , since there is no "undefined" enter items , but it does not matter), and the condition is i++ and no update code. However, i++ evaluates the falsity of NaN , so your loop is immediately interrupted. And without a second semicolon, it's even like a SyntaxError.

Instead, you want a for-in-loop :

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

Btw, items.clean = true; will create a new property again, so the object will not really be "clean" :-)

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

No. You must combine all the properties and remove them.

+1
source

There is no shorter way, sorry. Your loop should not have i++ .

 function removeItems(items) { for(var i in items) { delete items[i]; } items.clean = true; } 

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

0
source

All Articles