peter
peter

Reputation: 2103

Clone array of objects fails

I fetch some fancy data from an MVC Controller and asign it to the global variable "data_Visits". Then, later in the party, I need to operate repeatedly on the original data in "data_Visits".

To not change values in "data_Visits", I thought to clone it and then operate on the clone. Still, the following seems to change values in "data_Visits":

var data = data_Visits.slice(0);

data.forEach(function (d) {
    d.date = new Date(ToJavaScriptDate(d.date));
    d.result1 = +d.result1;
    d.result2 = +d.result2;
});

Would anybody happen to know WHY?

Upvotes: 0

Views: 43

Answers (2)

james emanon
james emanon

Reputation: 11807

I agree, extend is what you want. If you use an array - you can use slice.

var d = {bob: 'yes'}
var b = jQuery.extend({}, d);

b.bob = 'no'
// shows b modified, d is not
console.log(b, d);

here is a nice referencde: How do I correctly clone a JavaScript object?

Upvotes: 1

zerkms
zerkms

Reputation: 254916

Because you're making a clone of an array of references. You need to clone each array entry specifically, otherwise both arrays would contain the different collections of references to the same objects.

What you need to do is called a deep copy.

As soon as you've specified jquery tag - here is an example:

var data = $.extend(true, [], data_Visits);

References:

PS: as a simple example:

This is what you basically do:

var a = { foo: 'bar' };
var b = a;

and even though you have 2 variables - they refer to the same object.

Upvotes: 1

Related Questions