Dado
Dado

Reputation: 1026

Push object in Javascript

I need to push object to array in Javascript, but every time push overwrite the same object I have had already added. For example:

//This is object list
var NewIssue = {};
//This is array
var newIssueList = [];

function myFunction() {
    for (var i = 0; i < 3; i++) {
        NewIssue.Id = i;
        NewIssue.Number = 233 + i;
        NewIssue.Name = "Test" + i.toString();

        newIssueList.push(NewIssue);
    }
}

In the end I will have newIssueList with 3 same objects. Why it does overwrite the first and how to solve this problem?

Upvotes: 3

Views: 11812

Answers (3)

Ori Drori
Ori Drori

Reputation: 191946

There is only one object, and each time you push it into the array, you push a reference to the existing object. When you change the object, every element in the array reflects this, as they all point to the same object.

You need to create a new object on every iteration.

//This is array
var newIssueList = [];

function myFunction() {
  for (var i = 0; i < 3; i++) {
    newIssueList.push({
      id: i,
      number: 233 + i,
      name: "Test" + i.toString()
    });
  }
}

myFunction();

console.log(newIssueList);

Upvotes: 2

kind user
kind user

Reputation: 41893

You have to move the object inside the loop.

var newIssueList = [];

function myFunction() {
    for (var i = 0; i < 3; i++) {
        var NewIssue = {};
        NewIssue.Id = i;
        NewIssue.Number = 233 + i;
        NewIssue.Name = "Test" + i.toString();

        newIssueList.push(NewIssue);
    }
}

myFunction();

console.log(newIssueList);

And then you could just extend the object literal a but to make it much more readable:

    for (var i = 0; i < 3; i++) {
        var NewIssue = {
           Id:i,
           Number:233+i,
           Name:"Test"+i
        };

        newIssueList.push(NewIssue);
    }

Upvotes: 5

Jim Cote
Jim Cote

Reputation: 1756

You can also avoid using a superfluous var by creating an inline object:

newIssueList.push({
    Id: i,
    Number: 233 + i,
    Name: "Test" + i.toString()
});

Upvotes: 3

Related Questions