3

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?

2

3 Answers 3

5

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);
    }
Sign up to request clarification or add additional context in comments.

Comments

3

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

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

Comments

2

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.