Alter and Assign Object Without Side Effects

I currently have the following code:

var myArray = [];
var myElement = {
  id: 0,
  value: 0
}

myElement.id = 0;
myElement.value = 1;
myArray[0] = myElement;

myElement.id = 2;
myElement.value = 3;
myArray[1] = myElement;

The problem is that when I change the value of id and value for my second element, the values also change in the first element. Is there a way that I can keep adding new elements without it changing the value of the previously inserted values in the array?


Solution 1:

Try this instead:

var myArray = [];

myArray.push({ id: 0, value: 1 });
myArray.push({ id: 2, value: 3 });

or will this not work for your situation?

Solution 2:

This is a textbook case for a constructor function:

var myArray = [];

function myElement(id, value){
    this.id = id
    this.value = value
}

myArray[0] = new myElement(0,1)
myArray[1] = new myElement(2,3)
// or myArray.push(new myElement(1, 1))

Solution 3:

You either need to keep creating new objects, or clone the existing one. See What is the most efficient way to deep clone an object in JavaScript? for how to clone.