Several methods of implementing deep copy in JS

1. Use JSON conversion

This is the easiest way.

JSON.parse(JSON.stringify(obj))

2. Use recursion

The object is traversed recursively and the value of each property is copied. Need to handle the case where the copied object is a value type and the case where the property value contains an object. It should be noted that in order to prevent circular references from causing infinite loops, it is necessary to record the objects that have been traversed.

const deepClone = obj => {
    
    
  if (typeof obj !== 'object' || obj === null) {
    
    
    return obj;
  }
  let result = Array.isArray(obj) ? [] : {
    
    };
  for (let key in obj) {
    
    
    if (obj.hasOwnProperty(key)) {
    
    
      result[key] = deepClone(obj[key]);
    }
  }
  return result;
}

3. With the help of plug-ins

Lodash

LodashIt is a consistent, modular, high-performance JavaScriptutility library.

npm i --save lodash
import {
    
    cloneDeep} from 'lodash';
const obj1 = {
    
    a: {
    
    b: 2}};
const obj2 = cloneDeep(obj1);

END

Guess you like

Origin blog.csdn.net/m0_53808238/article/details/130903197