I am copying myObj
to tempMyObj
var tempMyObj = myObj;
tempMyObj.entity
is an array of objects. I am modifying tempMyObj.entity
based on some conditions. The problem is if I modify tempMyObj.entity
the myObj.entity
is also getting modified.
for (j = 0; j < myObj.length; j++) {
if (myObj[j].type == "TableShape") {
var dupEntites = new Array();
for (i = 0; i < myObj[j].entities.length; i++) {
if (chk.value != myObj[j].entities[i].id) {
var obj = {};
obj.text = myObj[j].entities[i].text;
obj.id = myObj[j].entities[i].id;
dupEntites.push(obj);
}
else {
if (chk.checked)
{
var obj = {};
obj.text = myObj[j].entities[i].text;
obj.id = myObj[j].entities[i].id;
dupEntites.push(obj);
}
}
}
tempMyObj[j].entities = dupEntites;
}
}
This might be very tricky, let me try to put this in a simple way. When you "copy" one variable to another variable in javascript, you are not actually copying its value from one to another, you are assigning to the copied variable, a reference to the original object. To actually make a copy, you need to create a new object use
The tricky part is because there's a difference between assigning a new value to the copied variable and modify its value. When you assign a new value to the copy variable, you are getting rid of the reference and assigning the new value to the copy, however, if you only modify the value of the copy (without assigning a new value), you are modifying the copy and the original.
Hope the example helps!
It is clear that you have some misconceptions of what the statement
var tempMyObj = myObj;
does.In JavaScript objects are passed and assigned by reference (more accurately the value of a reference), so
tempMyObj
andmyObj
are both references to the same object.Here is a simplified illustration that may help you visualize what is happening
As you can see after the assignment, both references are pointing to the same object.
You need to create a copy if you need to modify one and not the other.
Old Answer:
Here are a couple of other ways of creating a copy of an object
Since you are already using jQuery:
With vanilla JavaScript
See here and here
Try using the create() method like as mentioned below.
This will solve the issue.
Try using $.extend():