In JavaScript, implement deep copy of objects

In JavaScript, implement deep copy of objects

  1. Manually implement deep copy function
    Manually implement deep copy function can realize deep copy of object and its nested properties through recursion, for example:
function deepCopy(obj) {
    
    
  let copy = Array.isArray(obj) ? [] : {
    
    };
  for (let key in obj) {
    
    
    if (typeof obj[key] === "object") {
    
    
      copy[key] = deepCopy(obj[key]);
    } else {
    
    
      copy[key] = obj[key];
    }
  }
  return copy;
}

2. Use JSON serialization and deserialization
. JSON.stringify() and JSON.parse() can be used to realize deep copy of objects. However, this method has certain limitations. For example, functions and prototype chains cannot be copied, and at the same time, they cannot be copied. Circular reference to objects.

let obj = {
    
     foo: "bar", arr: [1, 2, 3], obj: {
    
     a: 1, b: 2 } };
let copy = JSON.parse(JSON.stringify(obj));

3. Use third-party libraries.
Use third-party libraries such as lodash, underscore, etc. to quickly and easily implement deep copies of objects.

const _ = require('lodash');
let obj = {
    
     foo: "bar", arr: [1, 2, 3], obj: {
    
     a: 1, b: 2 } };
let copy = _.cloneDeep(obj);

4. Use the ES6 Object.assign() method.
The Object.assign() method can copy the properties of multiple objects to the target object, and can also implement shallow copy and deep copy, but it cannot handle deep copying of nested objects.

let obj = {
    
     foo: "bar", arr: [1, 2, 3], obj: {
    
     a: 1, b: 2 } };
let copy = Object.assign({
    
    }, obj);

end

Guess you like

Origin blog.csdn.net/NIKKT/article/details/130427025