Several methods of object deep copy

1. Conversion through json (larger limitations)

  var obj={name:'aab',age:20};
  var newObj=JSON.parse(JSON.stringify(obj))

Two, ES6 destructuring assignment

 var obj = {name:'123',age:13};
 var obj2 = {...obj}

Three, for in loop through objects

 var obj = {
    name: "小明",
    age: 20
  }
  var obj1 = {}
  for (var key in obj) {
    //遍历属性值,深拷贝
    obj1[key] = obj[key]
  }
  console.log(obj1);

4. Object.assign() Merge of Objects

 var obj = {name:'123',age:13};
 var obj2 = Object.assign({},obj1);
 console.log(obj1);//{name:'123',age:13}

The above methods can only copy one layer, and cannot deeply copy the object properties in the object

Guess you like

Origin blog.csdn.net/weixin_53583255/article/details/126615589