0

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?

peter
  • 2,103
  • 7
  • 25
  • 51

2 Answers2

1

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.

zerkms
  • 249,484
  • 69
  • 436
  • 539
  • Dooh! Sounds so wonderfully logical. Deep Copy, thanks, will try that in an instance. – peter Nov 08 '13 at 00:23
  • your original code looks to be pure javascript. Are you using a library such as jQuery? – Michael Nov 08 '13 at 00:24
  • yes, I use jQuery. zerkms, the cloning is successfull, but now I get an error when I try to iterate via data.forEach() – peter Nov 08 '13 at 00:26
  • well, "data" is being shown as function(). I lack the words to describe it better, but the original "data_Visits" is just an array of objects and the clone "data" has all the data PLUS the notion of function() and prototype.. – peter Nov 08 '13 at 00:29
  • @peter: it's my fault. See the modified answer. When `deep` is specified - you need to both specify `target` and `src` arrays – zerkms Nov 08 '13 at 00:30
1

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?

Community
  • 1
  • 1
james emanon
  • 11,185
  • 11
  • 56
  • 97