JSON.parse(JSON.stringify(obj))

This line of code serializes the JS object (JSON string) using json.stringify, and then deserializes (restores) the JS object using json.parse. Serialization is for storage and transport. (stored in the object itself is an address mapping, if the power is, the object will not exist, so will the contents of the object is transformed into the form of a string stored in the disk), however, the realization method of the deep copy has limitations, it is only applicable to general data copy (objects, arrays), has the following situation need to pay attention to:

1. If there is a time object in json, serialize the result: time object => string;

{
    let obj = {
        age: 18,
        date: new Date()
    };
    let objCopy = JSON.parse(JSON.stringify(obj));
    console.log('obj', obj);
    console.log('objCopy', objCopy);
    console.log(typeof obj.date); // object
    console.log(typeof objCopy.date); // string
}
Copy the code

Error => {}; RegExp => {}; Error => {};

{
    let obj = {
        age: 18,
        reg: new RegExp('\w+'),
        err: new Error('error message')
    };
    let objCopy = JSON.parse(JSON.stringify(obj));
    console.log('obj', obj);
    console.log('objCopy', objCopy);
}
Copy the code

If json contains function,undefined, function,undefined will be lost in the serialization result;

{
    let obj = {
        age: 18,
        fn: function () {
            console.log('fn');
        },
        hh: undefined
    };
    let objCopy = JSON.parse(JSON.stringify(obj));
    console.log('obj', obj);
    console.log('objCopy', objCopy);
}
Copy the code

4. If the json contains NaN, Infinity, and -infinity, the serialized result will be null;

{let obj = {age: 18, hh: NaN, isInfinite: 1.7976931348623157E+10308, minusInfinity: -1.7976931348623157e +10308}; let objCopy = JSON.parse(JSON.stringify(obj)); console.log('obj', obj); console.log('objCopy', objCopy); }Copy the code

5. If an object in json is generated by a constructor, the serialized result will discard the object’s constructor;

{
    function Person(name) {
        this.name = name;
    }
    let obj = {
        age: 18,
        p1: new Person('lxcan')
    };
    let objCopy = JSON.parse(JSON.stringify(obj));
    console.log('obj', obj);
    console.log('objCopy', objCopy);
    console.log(obj.p1.__proto__.constructor === Person); // true
    console.log(objCopy.p1.__proto__.constructor === Object); // true
}
Copy the code

6. Deep copy cannot be implemented if circular references exist in the object

{
    let obj = {
        age: 18
    };
    obj.obj = obj;
    let objCopy = JSON.parse(JSON.stringify(obj));
    console.log('obj', obj);
    console.log('objCopy', objCopy);
}
Copy the code

Parse (json.stringify (obj)) can be used to implement deep copy if the copied object does not involve the above situation.