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?

asked Jul 22, 2017 at 16:37
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);
 }
Jonas Wilms
139k20 gold badges164 silver badges164 bronze badges
answered Jul 22, 2017 at 16:39
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()
});
answered Jul 22, 2017 at 16:41

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

answered Jul 22, 2017 at 16:42

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.