Deep Clone Objects in Javascript – Introducing a Powerful Solution

by xthemes content creator
15 minutes read

Article courtesy of author Son Duong

Many people work with Javascript but have you ever come across a situation where you need to clone something? Have you ever edited something and changed the same thing? For example, a particular problem is that you create an object that stores the default configuration. After that, depending on the function, it is necessary to copy the default configuration and edit it. When I come back later, the default configuration object is also changed. Weird!?

Problem when copying a Javascript object

To make it easier for you to think, I give an example with the code when you copy something:

tao cv online cn
const defaultConfig = {
  debug: true,
  name: "Cấu hình mặc định",
  connectType: "Wifi",
}

const customConfig = defaultConfig;
customConfig("debug") = false;
customConfig("name") = "Cấu hình cho KH";

console.log(defaultConfig);

Result:

deep-clone-object-javascript

So even if you don’t edit defaultConfig but also changed after the update customConfig.

The cause of the above problem is related to reference and value data types. In Object it is a reference data type. Wakes are variables that store only the memory address of the object. So when that variable is assigned to another variable, it essentially creates two variables that point to the same area of ​​memory.

Therefore, deep cloning an object is a way of creating a new memory area separate from the original memory.

Deep Clone Objects

Ok, after understanding the problem and nature, let’s try some ways to deep clone an object in javascript.

1. Use the Spread operator

Spread is the operator that “flattens” something. Therefore, after “flattening” you need to create a new object via {} syntax.

const defaultConfig = {
  debug: true,
  name: "Cấu hình mặc định",
  connectType: "Wifi",
}

const customConfig = {...defaultConfig};
customConfig("debug") = false;
customConfig("name") = "Cấu hình cho KH";

console.log(defaultConfig);
// {debug: true, name: "Cấu hình mặc định", connectType: "Wifi"}

The downside of this method is that it only works on non-nested objects. But Objects with multiple nested levels are “out of magic”.
Example:

const defaultConfig = {
  debug: true,
  name: "Cấu hình mặc định",
  connectType: "Wifi",
  data: {
    position: 1
  }
}

const customConfig = {...defaultConfig};
customConfig("debug") = false;
customConfig("name") = "Cấu hình cho KH";
customConfig("data")("position") = 2

console.log(defaultConfig);
// {debug: true, name: "Cấu hình mặc định", connectType: "Wifi", data: { postion: 2}}

That’s not possible. Stronger measures should be used (refer to method number 2 that I introduced at the end of the article)

JavaScript Ho Chi Minh jobs for you!

2. Use Object.assign

This solution is similar to using the Spread operator.

const defaultConfig = {
  debug: true,
  name: "Cấu hình mặc định",
  connectType: "Wifi",
}

const customConfig = Object.assign({}, defaultConfig);
console.log(defaultConfig);
// {debug: true, name: "Cấu hình mặc định", connectType: "Wifi"}

The only difference in using the Spread operator is that the function Object.assign() is the ability to support more browsers.

3. A very powerful proposal is to use JSON

If the above two solutions do not meet your deep clone requirements, this is a powerful medicine that will solve your problem.

That uses the function JSON.parse() combined with JSON.stringify().

const defaultConfig = {
  debug: true,
  name: "Cấu hình mặc định",
  connectType: "Wifi",
}

const customConfig = JSON.parse(JSON.stringify(defaultConfig));

This solution looks a bit funny at first, but it is actually quite capable.

4. Write your own clone object

If you want to master the deep clone Object technology by yourself, we can write the create object function by ourselves. By recursively iterating through each property of the original object and creating a new object.

function cloneObject(obj) {
  var clone = {};
  for(var i in obj) {
      if(obj(i) != null && typeof(obj(i))=="object")
          clone(i) = cloneObject(obj(i));
      else
          clone(i) = obj(i);
   }
   return clone;
}

// Cách sử dụng
const defaultConfig = {
  debug: true,
  name: "Cấu hình mặc định",
  connectType: "Wifi",
  data: {
    position: 1
  }
}

const customConfig = cloneObject(defaultConfig)
customConfig("debug") = false;
customConfig("data")("position") = 2;
console.log(defaultConfig);
// {debug: true, name: "Cấu hình mặc định", connectType: "Wifi", data: {position: 1}}

Completion

Above are some ways you can deep Clone Objects in Javascript. I hope this will be useful for your project.

The original article was posted on vntalking.com

Find the latest IT jobs on TopDev

Related Posts

Leave a Comment