2

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});
  }
}

3 Answers 3

6
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.

Sign up to request clarification or add additional context in comments.

2 Comments

Also, if your key names are the same you can just do players[i] = msg
@adam That inserts a reference to msg inside players. Copying the fields over one by one creates an independent new object.
2

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.

Comments

0

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';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.