I currently have the following code:
var myArray = [];
var myElement = {
id: 0,
value: 0
}
myElement.id = 0;
myElement.value = 1;
myArray[0] = myElement
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);
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?
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.
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;
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))