Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate associative array and delete some elements in JSLint way (JavaScript, node.js 4.2.3)

I wrote code:

for (var game in this.currentGames) {
    if (this.currentGames[game].gameState === consts.GS_GAME_DELETE) {
        delete this.currentGames[game];
    }
}

It works fine, but JSLint.net show me warning:

JSLint : Unexpected 'var'.

When I tried to fix it:

var game;
for (game in this.currentGames) {
    if (this.currentGames[game].gameState === consts.GS_GAME_DELETE) {
        delete this.currentGames[game];
    }
}

I get such warning: JSLint : Expected 'Object.keys' and instead saw 'for in'.

I tried to fix and wrote next code:

Object.keys(this.currentGames).forEach(function (item, i, arr) {
    if (arr[i].gameState === consts.GS_GAME_DELETE) {
        delete arr[i];
    }
});

It just not works, because arr is array (not associative array).

When I try to:

Object.keys(this.currentGames).forEach(function (item) {
    if (this.currentGames[item].gameState === consts.GS_GAME_DELETE) {
        delete this.currentGames[item];
    }
});

I get run-time error:

if (this.currentGames[item].gameState === consts.GS_GAME_DELETE) {
        ^

TypeError: Cannot read property 'currentGames' of undefined

I use Microsoft Visual Studio 2012 and JSLint.NET.

So, my question is: is where right way for deleting element from associative array in cycle? Or is where way to shut JSLint up?

like image 235
n4meless0nly Avatar asked Jun 11 '26 01:06

n4meless0nly


1 Answers

for (var game in this.currentGames) {
  if (this.currentGames.hasOwnProperty(game)
    && this.currentGames[game].gameState === consts.GS_GAME_DELETE
  ) {
    delete this.currentGames[game];
  }
}

You also may use your last variant by define some variable with this value out of anonymous function scope (which has its own this context):

var self = this;
Object.keys(this.currentGames).forEach(function (item) {
  if (self.currentGames[item].gameState === consts.GS_GAME_DELETE) {
    delete self.currentGames[item];
  }
});
like image 98
Max Zuber Avatar answered Jun 13 '26 16:06

Max Zuber



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!