code Zero
code Zero

Reputation: 115

Array duplicate object while pushing object

When I am trying to push object on the array its duplicate all the object to the last pushed object.

 var seriesArr = [];
 var seriesDemo = {};

 var seriesFinal = finalArr[0]

 for (var o in finalArr[0]) {
    seriesDemo.valueField = o;
    seriesArr.push(seriesDemo);
 }

OUTPUT:

[{"valueField":"amount[3]"},{"valueField":"amount[3]"},{"valueField":"amount[3]"},{"valueField":"amount[3]"}]

It should be like: [{"valueField":"amount[0]"},{"valueField":"amount[1]"},{"valueField":"amount[2]"},{"valueField":"amount[3]"}]

Upvotes: 2

Views: 1173

Answers (1)

phreakv6
phreakv6

Reputation: 2165

Maybe you are looking for this?

for (var o in finalArr[0]) {
   var seriesDemo = {}; // (Re-)Initialize here
   seriesDemo.valueField = o;
   seriesArr.push(seriesDemo);
}

The problem is that you are updating the global seriesDemo hash everytime and it is pushed into seriesArr by reference. So all entries in seriesArr are holding reference to the last entry.

Upvotes: 4

Related Questions