Deep copy of objects in vue

define an object by yourself, because the object needs to perform bidirectional data binding operation, so it is necessary to back up the initial state of the object because of the development needs. However, the invalidity of the ordinary backup object will still cause the backup object to change because of bidirectional data binding. Please tell me how to back up the initial object with deep copy.

Mar.17,2021

function deepClone(data){
       var type = getType(data);
       var obj;
       if(type === 'array'){
           obj = [];
       } else if(type === 'object'){
           obj = {};
       } else {
           //
           return data;
       }
       if(type === 'array'){
           for(var i = 0, len = data.length; i < len; iPP){
               obj.push(deepClone(data[i]));
           }
       } else if(type === 'object'){
           for(var key in data){
               obj[key] = deepClone(data[key]);
           }
       }
       return obj;
   }

generally use JSON.parse (JSON.stringify (data). If you want to use this method, there are several notes you need to know


you can use the cloneDeep function of lodash .

use immutable , officially issued by facebook. All data are immutable and do not require operations such as deep copy

.

for pure data objects, you can use the interface of JSON.

var obj_snapshot = JSON.parse(JSON.stringify(obj))

if it is a js object with function, then. To be more complicated, write a clone

Menu