Alex W. Alex W. - 4 months ago 20
Javascript Question

dojo array.push replaced the previous item

the following javascript returns

personNames
as

[{"name":"smith"},{"name":"smith"},{"name":"smith"}]


instead of

[{"name":"john"},{"name":"doug"},{"name":"smith"}]




var personNames = [];
var personName = {};

var persons = [{"firstname": "john", "id": "111"}, {"firstname": "doug", "id": "777"}, {"firstname": "smith", "id": "888"}];

if(persons.length > 0){
array.forEach(persons, function(person){
personName.name = person.firstname;
personNames.push(personName);
});
}




Answer
  array.forEach(persons, function(person){
  personName.name = person.firstname;
  personNames.push(personName);
  });

personName refers to the same object in each iteration. JavaScript keeps a reference to that object in memory, so when you update it later on, it updates everywhere, including inside the array.

For your use-case, you need to re-initialize personName each time:

  array.forEach(persons, function(person){
  personName = {};
  personName.name = person.firstname;
  personNames.push(personName);
  });

(Is the first line supposed to be persons.forEach(function(person){?)