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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With