test
test

Reputation: 18198

JavaScript updating an array element with index

I currently have an arrayList() called players in JavaScript in which I push data into it using: players.push({name: msg.name, map: msg.map, coords: msg.coords});

Here is an example data: { name: 'weka', map: '5', coords: '12.4' } for example players[0].

Here is what I am doing:

for (var i = 0; i < players.length; ++i) {
  if (msg.name === players[i].name) {
    console.log("Updating  index ("+i+") player: " + msg.name);
    //players[i].push({name: msg.name, map: msg.map, coords: msg.coords});
  }
}

Upvotes: 2

Views: 163

Answers (3)

hasrthur
hasrthur

Reputation: 1490

players[i] - is object ({ name: 'weka', map: '5', coords: '12.4' } for example), not array If you want to set set props just use palyers[i]['prop'] = 'prop';

Upvotes: 0

xdazz
xdazz

Reputation: 160953

players.push({name: msg.name, map: msg.map, coords: msg.coords}); is OK,

What you did is players[i].push({name: msg.name, map: msg.map, coords: msg.coords});, players[i] is not an array.

Upvotes: 2

Robin Castlin
Robin Castlin

Reputation: 10996

players[i].push({name: msg.name, map: msg.map, coords: msg.coords});

should be

players[i] = {name: msg.name, map: msg.map, coords: msg.coords});

You haven't defined players[i] to be an Array, so there's nothing to "push" to. And I asume that you wish to change existing value and not insert an extra depth.

Upvotes: 6

Related Questions