[javascript] 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?

This question is related to javascript

The answer is


Objects are passed by reference.. To create a new object, I follow this approach..

//Template code for object creation.
function myElement(id, value) {
    this.id = id;
    this.value = value;
}
var myArray = [];

//instantiate myEle
var myEle = new myElement(0, 0);
//store myEle
myArray[0] = myEle;

//Now create a new object & store it
myEle = new myElement(0, 1);
myArray[1] = myEle;

That's because object values are passed by reference. You can clone the object like this:

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

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

var obj = {};
obj = clone(myElement);
obj.id = 2;
obj.value = 3; 

myArray[1] = obj;

function clone(obj){
  if(obj == null || typeof(obj) != 'object')
    return obj;

  var temp = new obj.constructor(); 
  for(var key in obj)
    temp[key] = clone(obj[key]);

  return temp;
}    

console.log(myArray[0]);
console.log(myArray[1]);

Result:

 - id: 0
 - value: 1
 - id: 2
 - value: 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.


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

If you're using jQuery, you can use extend

myElement.id =0;
myElement.value=1;
myArray[0] = $.extend({}, myElement);

myElement.id = 2;
myElement.value = 3;
myArray[1] = $.extend({}, myElement);

You will have the same object two times in your array, because object values are passed by reference. You have to create a new object like this

myElement.id = 244;
myElement.value = 3556;
myArray[0] = $.extend({}, myElement); //for shallow copy or
myArray[0] = $.extend(true, {}, myElement); // for deep copy

or

myArray.push({ id: 24, value: 246 });