P粉3948122772023-08-28 17:35:35
To summarize, just to clarify, there are four ways to copy a JS object.
const a = { x: 0} const b = a; b.x = 1; // also updates a.x
...{}
or Object.assign()
. const a = { x: 0, y: { z: 0 } }; const b = {...a}; // or const b = Object.assign({}, a); b.x = 1; // doesn't update a.x b.y.z = 1; // also updates a.y.z
const a = { x: 0, y: { z: 0 } }; const b = JSON.parse(JSON.stringify(a)); b.y.z = 1; // doesn't update a.y.z
lodash
. import { cloneDeep } from "lodash"; const a = { x: 0, y: { z: (a, b) => a + b } }; const b = cloneDeep(a); console.log(b.y.z(1, 2)); // returns 3
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. P粉5205457532023-08-28 12:57:02
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
and myObj
are both references to the same object.
This is a simplified illustration to help you visualize what is going on
// [Object1]<--------- myObj var tempMyObj = myObj; // [Object1]<--------- myObj // ^ // | // ----------- tempMyObj
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.
// [Object1]<--------- myObj const tempMyObj = Object.assign({}, myObj); // [Object1]<--------- myObj // [Object2]<--------- tempMyObj
Old answer:
Here are several other ways to create copies of objects
Since you are already using jQuery:
var newObject = jQuery.extend(true, {}, myObj);
Use plain JavaScript
function clone(obj) { if (null == obj || "object" != typeof obj) return obj; var copy = obj.constructor(); for (var attr in obj) { if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr]; } return copy; } var newObject = clone(myObj);