I've a strange problem while assigning the object to array in JavaScript here is complete code

var co = {'yAxis':10};

var dynCharts = new Array();

for (var x=0; x<2; x++){                  
    dynCharts[x] = co;   
}
//assigning to first array only 
dynCharts[0].yAxis = { 'a':'1'};
//now alert second array
alert(dynCharts[1].yAxis.a);

If you above example code first of all I've a object called co then i'm assigning that object to arrays. Now I want to change the property called yAxis of first array but it's changing the value for the yAxis object of second array too.

JSfiddle of this code is here : http://jsfiddle.net/qvKaZ/

Can somebody please help me why its happening how to do it in property way ?

share|improve this question
feedback

3 Answers

One way is to use Object.create, which will create a new object that inherits from co.

for (var x=0; x<2; x++){                  
    dynCharts[x] = Object.create(co);   
}

An advantage is that you can update co at any time, and all the objects that inherit from it will see the update, as long as the updated property is not shadowed on the actual object.

To handle older browsers, include this code.

if (!Object.create) {
   Object.create = function(proto) {
       Object.create.F.prototype = proto;
       return new Object.create.F;
   };
   Object.create.F = function(){};
}

It's not a fully compliant substitute, but will work for basic cases as used above

share|improve this answer
feedback

Every object in your array is a reference to the object. If you change the object at all, all values in the array will appear to be updated. You need to make a new object or clone the existing one on each iteration of your loop.

share|improve this answer
feedback

You have the same object (that is the same instance) in all the cells of your array.

You need to duplicate (clone) co so that one change doesn't apply to all cells :

for (var x=0; x<2; x++){                  
    dynCharts[x] = {yAxis:co.yAxis}; // this puts in dynCharts[x] a copy of co
}
share|improve this answer
ok thanks for answering quickly..I've figured it out after posting this question :) ... I've updated the jsfiddle now with and used jQuery function to clone the object - jsfiddle.net/qvKaZ/3 – roshanbh Sep 22 at 18:54
feedback

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.