0

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 ?

1

3 Answers 3

0

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
}
Sign up to request clarification or add additional context in comments.

1 Comment

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
0

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.