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?

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Dooh! Sounds so wonderfully logical. Deep Copy, thanks, will try that in an instance.
your original code looks to be pure javascript. Are you using a library such as jQuery?
yes, I use jQuery. zerkms, the cloning is successfull, but now I get an error when I try to iterate via data.forEach()
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: it's my fault. See the modified answer. When deep is specified - you need to both specify target and src arrays
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?

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.