Skip to content Skip to sidebar Skip to footer

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. ang

Solution 1:

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

Solution 2:

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.

Post a Comment for "Changing Single Object In Js Array Changes All Elements"