michaelp
michaelp

Reputation: 363

Changing single object in JS array changes all elements

I have an array of 71 objects:

var data = []

I populate this with data coming from a database that contains both static and dynamic elements of the objects that populate data.

angular.forEach(returnData,function(value,index) {
  if(!Array.isArray(value)) {
    tempObject[key] = value;
  }
});
for(i = 0; i < 71; i++) {
  data.push(tempObject);
}

So, in angular, I grab every element that is static from the return data, create an object of it, and repeat that same object 71 times. So the data might start out something like this:

[
  {'a': 1,
   'b': 2,
   'd': 7
  },
  {'a': 1,
   'b': 2,
   'd': 7
  }
]

I then go and grab all of the elements that are passed back as arrays and try and add them to the data array.

However, as soon as I add the first element, it sets that same element for every object in the array.

Meaning that data[0]['c'] = 11; will result in:

[
  {'a': 1,
   'b': 2,
   'c': 11,
   'd': 7
  },
  {'a': 1,
   'b': 2,
   'c': 11,
   'd': 7
  }
]

even though I haven't touched the second index in the array. And when I update the second index it will update the first index as well. I'm sure there is something that I'm missing here.

Thanks!

Upvotes: 1

Views: 1128

Answers (2)

Scott Hunter
Scott Hunter

Reputation: 49873

You said it yourself: the array contains the same object 71 times. Not 71 copies of an object, but the same single object referenced 71 times. Thus, changing that object via any of those references will be reflected in all references.

Upvotes: 1

Justin Niessner
Justin Niessner

Reputation: 245439

You're just pushing a reference to tempObject into 71 different positions in your data array. Therefore data[0], data[1], and so on are all pointing to the same object which is why you see changes reflected across the array.

If you want to actually push 71 separate instances, you have to clone tempObject every time you push it on to the array.

Last I checked, the most efficient way to clone a plain old JavaScript object was to string-ify and then re-parse:

data.push(JSON.parse(JSON.stringify(tempObject)));

Upvotes: 2

Related Questions