Reputation: 5280
I would like to know what is the better way to exectute this common action:
var id = 1;
var Players = [{ id: 0, other: '...'}, { id: 1, other: '...' }]
for (var i=0; i<Players.length; i++) {
if (Players[i].id == id) {
return i;
}
}
I was thinking about Array.map but i don't know if we can access the key:
Players.map(function(Player) { if (Player.id == id) { return ?? } });
Upvotes: 0
Views: 63
Reputation: 18462
You could also try reduce:
// The second argument is set to null so that reduce doesn't just
// start with the first object in the array
Players.reduce(function(memo, Player, key) {
return Player.id === id ? key : memo;
}, null);
Upvotes: 1
Reputation: 3891
Depending on your structure (and keeping performance in mind); making it an associative object/array could work out.
var object = { id: 1, other: '...' };
var Players = [];
Players[object.id] = object;
You can then reference the required Player by ID by doing:
var id = 1;
var playerObject = Players[id];
Please note that you cannot use negative or zero values for the ID in this case.
Upvotes: 1