Cloning objects in JavaScript is a common task for any project: from simple objects to complex ones.

Normally, the assignment operator does not generate a copy of the object. It can assign a reference to it.

Let’s look at the following code:

let object = {

a: 2.b: 3};let copy = object;

object.a = 5;

console.log(copy.a);

//Result

//a = 5;

Copy the code

Object variables are containers for newly initialized objects. The copy variable refers to the same object and is a reference to that object.

Objects {a: 2, b: 3,} indicate that there are two ways to achieve success. This approach can eliminate any form of invariance that leads to errors.

There is a simple way to copy an object: it loops over the original object, copying each property one by one. The code looks like this:

function copy(mainObject) {
let objectCopy = {}; //objectCopy ' 'will store a copy of the mainObject
let key;
for (key in mainObject) {
   objectCopy[key] = mainObject[key]; ` `// ' 'copies each property to objectCopy
  }
  return objectCopy;
}
const mainObject = {
  a: 1.b: 3.c: {
    x: 5.y: 4,}}console.log(copy(mainObject));

Copy the code

Please note, however, that there may be inherent problems such as:

  • ObjectCopy gets a new Object.prototype method that differs from the mainObject Object prototype method. But if we want a copy of the original object, that’s not what we want.
  • The property descriptor cannot be copied. Writable descriptors (including values set to false) will be true in the objectCopy object.
  • The code shown above copies the enumerable properties of the mainObject.
  • If the properties within the original object are objects, they can be shared between the copy and the original object.

Note that JavaScript objects are mutable by nature and stored as references. Therefore, when assigning an object to another variable, we assign the object’s memory address to that variable. In this case, the old object and the new object point to the same memory address. Every change in one is reflected in the other. Therefore, assigning one object to another does not copy the object.

Shallow copy with spain. Syntax or object. assign

The expansion syntax is one of the shortest and easiest ways to copy and/or merge objects.

The example would look like this:

let obj = {

  key1: value1,

 key2: value2

};

letclonedObject = { ... obj };console.log(clonedObject);

//Object { key1: value1, key2: value2 }
Copy the code

The object.assign () method is used to copy all enumerable attributes from one or more source objects to the target Object that returns them.

Here’s an example:


let obj = {

 key1: value1,

  key2: value2

};

let clonedObject = Object.assign({}, obj);

console.log(clonedObject);

//Object { key1: value1, key2: value2 }
Copy the code

Thus, the spread syntax and object.assign are standard methods for copying objects. They’re equivalent.

The problem with the above methods is that they implement shallow copies. Therefore, a new object is generated that gets an exact copy of the original object value. Note, however, that if any object field is a reference to another object, only the reference address is copied: only the memory address is copied.

The following is an example:

let obj = {
  a: 0.b: {
    c: 0}};letcopySpread = { ... obj };let copyOA = Object.assign({}, obj);

console.log(JSON.stringify(obj));  //{ a: 0, b: { c: 0}}

obj.a = 1;

console.log(JSON.stringify(obj));  //{ a: 1, b: { c: 0}}

console.log(JSON.stringify(copySpread));  //{ a: 0, b: { c: 0}}

console.log(JSON.stringify(copyOA));  //{ a: 0, b: { c: 0}}

copySpread.a = 2;

copyOA.a = 3

console.log(JSON.stringify(obj));  //{ a: 1, b: { c: 0}}

console.log(JSON.stringify(copySpread)); //{ a: 2, b: { c: 0}}

console.log(JSON.stringify(copyOA));  //{ a: 3, b: { c: 0}}

obj.b.c = 4;

console.log(JSON.stringify(obj));  //{ a: 1, b: { c: 4}}

console.log(JSON.stringify(copySpread));  //{ a: 2, b: { c: 4}}

console.log(JSON.stringify(copyOA));  //{ a: 3, b: { c: 4}}

Copy the code

Use json. stringify and json.parse

Deep copy occurs when we copy an object and the objects it refers to. We can create a deep copy by mixing json.stringify and json.parse.

First, we should parse json.stringify () its JSON object to get the object back. The json.parse () method aims to parse and construct JavaScript objects or values described by strings. Object’s new fields have their memory address and are independent of the nested object fields.

Here is an example of deep cloning:


//Deep Clone

obj = {

 a: 0.b: {

    c: 0}};let cloneObj = JSON.parse(JSON.stringify(obj));

obj.a = 2;

obj.b.c = 2;

console.log(JSON.stringify(obj)); //{ a: 2, b: { c: 2}}

console.log(JSON.stringify(cloneObj)); //{ a: 0, b: { c: 0}}

cloneObj.a = 4;

cloneObj.b.c = 4;

console.log(JSON.stringify(obj)); //{ a: 2, b: { c: 2}}

console.log(JSON.stringify(cloneObj)); //{ a: 4, b: { c: 4}}

Copy the code