evilReiko
evilReiko

Reputation: 20473

Javascript: In a loop, modify property of object then push to array

I have the following code (which works correctly):

var arr = [];
for(var i = 0; i < 2; i++) {
    var obj = { a: 'A'};
    obj.c = 'C' + i;
    arr.push(obj);
}

// now arr is:
// [ {a: 'A', 'c': 'C0'}, {a: 'A', 'c': 'C1'} ]

To improve the performance of my code, I placed the obj outside the loop, then adding/modifying the new property only, like this:

var arr = [];
var obj = { a: 'A'};
for(var i = 0; i < 2; i++) {
    obj.c = 'C' + i;
    arr.push(obj);
}

// now arr is:
// [ {a: 'A', 'c': 'C1'}, {a: 'A', 'c': 'C1'} ]

Why both objects got C1 ? Please explain what I'm doing wrong, and how to place the object out of the loop and get correct results?

Note: I know this is a simple problem where performance is not an issue, but I'm actually dealing with big number of objects in reality where performance matters.

Upvotes: 0

Views: 199

Answers (2)

Lain
Lain

Reputation: 3726

Like the others wrote, you are changing the same object (the original) all the time which ends in the results being the same (the original).

To place the object out of the loop and still get the correct result, you would still have to 'copy' it inside of the loop:

var arr = [];
var obj = { a: 'A'};
var objstring = JSON.stringify(obj);
for(var i = 0; i < 2; i++) {
    var obj = JSON.parse(objstring);
    obj.c = 'C' + i;
    arr.push(obj);
}

Upvotes: 1

Quentin
Quentin

Reputation: 943193

You are pushing the object (not a copy of the object) to the array, and then changing it.

If you want different objects in each index, then you need to create a new object each time you go around the loop.

Upvotes: 9

Related Questions