Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Copying backup Object seems to copy in reverse direction

Finally had a problem that I can reproduce in small code. Result is in Console. Is the snippit background considered the same as Global?

Copying an array into Object (from [] format) works (first example), but (second example) setting one element of an array in it and then copying it to another object property seems to copy the property in reverse direction.

var obj = {   //obj should be global, and the code below in a function,
    var1: [],
    var2: []  //But still same failure
}

obj.var1 = [1, 10, 1]; //first values
obj.var2 = obj.var1; //save backup globally in var2 between function calls
// ...
obj.var1 = [0, 2, 0]; //a new function call with new value in val1
// ...
obj.var1 = obj.var2; //and then overwrite and restore first values
console.log("1. This works: var1 = " + obj.var1 + ", var2 = " + obj.var2);
// both are [1,10,1] as expected

obj.var1[1] = 99;  //another new value, in one array index
// ...
obj.var1 = obj.var2; //and then restore first values again
console.log("2. Appears to copy the reverse  direction:\nvar1 = " + obj.var1 + ",  var2 = " + obj.var2);

//2.expects both var1 and var2 to be [1, 10, 1] but Both become [1, 99, 1] ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Objects and arrays in Javascript are reference type. When you are doing obj.var1 = obj.var2; it copies reference to var1 and both var1 and var2 pointing to same object. When you update any of them, both are updated. To avoid that, you should do deep copy. Copy individual elements of your array to var1. Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_objects#comparing_objects

If you copy elements instead of assigning whole array, it should work as expected.

obj.var1 = [...obj.var2]`
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading