The deep copy of the object in JavaScript has always been a bit more disgusting after all, there is no API directly full copy of their own convenience write recently in the project need to deep copy oneself simple sealed a method
Not much to say directly on the code
1 <!DOCTYPE html>
2 <html lang="en">
3 <head>
4 <meta charset="UTF-8">
5 <meta name="viewport" content="width=device-width, initial-scale=1.0">
6 <meta http-equiv="X-UA-Compatible" content="ie=edge">
7 <title>Document</title>
8 </head>
9 <body>
10 <script>
11 function deepCopy(arr_obj){
12 //The constructor property returns a reference to the array function that created this object.
13 let obj_arr = arr_obj.constructor === Array ? [] : {};
14 for(let key in arr_obj){
15 //Object.prototype.toString.call() type judgment
16 //Object.prototype.toString.call(obj_arr) returns [object Object] or [object Array]
17 if(Object.prototype.toString.call(arr_obj[key]) === ‘[object Object]‘){
18 obj_arr[key] = deepCopy(arr_obj[key]);
19 }else{
20
21 if(Object.prototype.toString.call(arr_obj[key]) === ‘[object Array]‘){
22 //console.log(arr_obj[key]);
23 arr_obj[key].forEach((item,index)=>{
24 if(Object.prototype.toString.call(item) === ‘[object Object]‘){
25 obj_arr[key][index] = deepCopy(item);
26 }else{
27 obj_arr[key] = [];
28 obj_arr[key][index] = item;
29 }
30 })
31 }else{
32 obj_arr[key] = arr_obj[key];
33 }
34 }
35 }
36
37 return obj_arr
38 }
39 let objA = {
40 a: 123,
41 b:[‘a‘,‘c‘,{‘a‘:[‘a‘,‘b‘,[‘c‘,‘d‘,{e:‘c‘}]]}],
42 c: ‘yyyy’
43 }
44 let objB = deepCopy(objA);
45 objA.a = 456
46 objA.b.push(‘yyyy‘);
47 console.log(objA,objB);
48
49 </script>
50 </body>
51 </html>
This method can be copied so far. The value of the object has an array. There are objects in the array. There are arrays in the array. There are some nestings. The complex data structure has not been tested. However, this is basically enough.
I changed objA.a and objA.b.push(‘yyyy‘);