Js deep copy object

Difference between shallow copy and deep copy Shallow copy: Copies only the basic property values of objects, and copies Pointers to properties whose property values are objects or arrays. Deep copy: Copies all properties of an object as a brand new object. Objects before and after the copy do not affect each other.

Shallow copy of literal properties

    var a = {name:"test".children: {name:"test1"}}
    / / shallow copy
    var b = {
        name:a.name,
        children:a.children
    }
    a.name = "Literal property copy"
    a.children.name = "Shallow copy"
    console.log(a)// children: Object{name:" copy "}}
    console.log(b)//Object {name:" test", children: Object{name:" shallow copy "}}
Copy the code

It can be seen that the shallow copy only copies the underlying property values of the object, and only copies the reference values of the object or array. Therefore, when modifying A. name, the attribute value of name is a string, so it is directly copied. The modification of A does not affect B. When the a.child property is modified, only the reference is copied because the property value is an object, so B. child is also changed

Deep copy of literal properties

var a = {name:"test".children: {name:"test1"}}
/ / copy
var b = {
    name:a.name,
    children: {name:a.children.name}
}
a.name = "Literal property copy"
a.children.name = "Shallow copy"
console.log(a)// children: Object{name:" copy "}}
console.log(b)//Object {name: "test", children: Object{name:"test1"}}
Copy the code

A deep copy is a further parsing of the shallow copy until all the properties are the underlying property values, so the deep-copy object is a completely separate new object.

Deep-copy public method encapsulation

// Returns the class of any object passed to him
const isClass = (o) = > {
  if (o === null) return "Null";
  if (o === undefined) return "Undefined";
  return Object.prototype.toString.call(o).slice(8, -1);
}


// Use recursive deep cloning
const deepClone = (obj) = > {
  if(! obj) {return null }
  let result, oClass = isClass(obj);
  // Determine the type of result
  if (oClass === "Object") {
    result = {};
  } else if (oClass === "Array") {
    result = [];
  } else {
    return obj;
  }

  for (let key in obj) {
    if (obj.hasOwnProperty(key)) {
      let copy = obj[key];
      if (isClass(copy) == "Object") {
        result[key] = deepClone(copy);// recursive call
      } else if (isClass(copy) == "Array") {
        result[key] = deepClone(copy);
      } else{ result[key] = obj[key]; }}}return result;
}
Copy the code

Note: ES6 provides an object.assign () method for copying and merging objects. However, this method is only a shallow copy method. Use this method with caution.