Deep copy and shallow copy - deep parsing

Keywords: Javascript JSON JQuery

Preface

For basic types such as numbers, boolean, and strings, assignment, shallow copy, and deep copy are meaningless because each time a new space is opened up in the heap, pointing to a new address.

1. Assignment:

Point to the same address, do not copy.

var obj1 = {name:'circular', radius:10, point:{x:0,y:0}};
var obj2 = obj1;
 
obj2.name = "Circle 2";  //The name in obj 1 will also change

2. Shallow copy:

var obj1 = {name:'circular', radius:10, point:{x:0,y:0}};
var obj2 = Object.assign({},obj1);
 
obj2.name="Circle 2"  // Obg1.name will not change
obj2.point.x = 2       //Obj 1. Point. X changed because it was copied to the point layer only

//The same is true of deconstruction assignment
var obj1 = {name:'circular', radius:10, point:{x:0,y:0}};
var obj2 = {...obj1}

III. deep copy:

Method 1

JSON.stringify(obj) first converts the object to a string
JSON.parse(str) then converts the string to an object.

var obj1 = {name:'circular', radius:10, point:{x:0,y:0}};
var obj2 = JSON.stringify(obj1 );
var obj1 = JSON.parse(obj2);
 
obj2.name = "Circle 2";  // obj1 unchanged
obj2.point.x = 3;     //  obj1 unchanged

However, when JSON.stringify transforms Date, RegExp objects and functions, problems will occur, and undefined and function will also be ignored.

//date type
var o = new Date();
console.log(o.toString());         //  Mon Nov 06 2017 11:23:35 GMT+0800 (China Standard Time) local standard time
console.log(JSON.stringify(o));    // "2017-11-06T03:23:35.547Z" international standard time

Because stringify calls the Object's toJSON method by default, rewrite the Date's toJSON, and then stringify is ok.

Date.prototype.toJSON = function () {
  return this.toLocaleString();
}
console.log(JSON.stringify(o));      // "11/6/2017, 11:23:35 AM"

Similarly RegExp

//RegExp type
r1 = /\d+/;
console.log(JSON.stringify(r1));           //   {}
 
RegExp.prototype.toJSON = function(){
return this.toString();
}
console.log(JSON.stringify(r1));          //    "/\\d+/" 

Method 2

The method of the class library. jquery,lodash, etc

//jquery
let  y = $.extend(true,{},x)   //The first parameter must be true

//lodash Library
let  y = _.cloneDeep(x);

Posted by lenhewitt on Sun, 08 Dec 2019 21:57:38 -0800