Modifying a copy of a JavaScript object causes changes to the original object
P粉765684602
2023-08-27 18:32:45
<p>I'm copying <code>objA</code> to <code>objB</code></p>
<pre class="brush:php;toolbar:false;">const objA = { prop: 1 },
const objB = objA;
objB.prop = 2;
console.log(objA.prop); // logs 2 instead of 1</pre>
<p>Arrays also have the same problem</p>
<pre class="brush:php;toolbar:false;">const arrA = [1, 2, 3],
const arrB = arrA;
arrB.push(4);
console.log(arrA.length); // `arrA` has 4 elements instead of 3.</pre>
<p><br /></p>
To summarize, just to clarify, there are four ways to copy a JS object.
...{}
orObject.assign()
.lodash
.Object.create()
indeed creates a new object. These properties are shared between objects (changing one changes the other). The difference from a normal copy is that the properties are added to the new object's prototype__proto__
. This can also be used as a shallow copy when you never change the original object, but I recommend using one of the above methods unless you specifically need this behavior.Obviously, you have some misunderstanding about what the statement
var tempMyObj = myObj;
does.In JavaScript, objects are passed and allocated by reference (more precisely, the value of the reference), so
tempMyObj
andmyObj
are both references to the same object.This is a simplified illustration to help you visualize what is going on
As you can see after the assignment, both references point to the same object.
If you need to modify one but not the other, you will need to create a copy.
Old answer:
Here are several other ways to create copies of objects
Since you are already using jQuery:
Use plain JavaScript
See here and here