Question 49: how to implement an object deep copy?

Time:2021-9-21

Suppose we want to copy an object. If we don’t make a deep copy of it, after changing one object, the other object will also change

Normal scenario

let a = {
    age: 20
};

let b = a;

b.age = 30;

console.log(a.age); // 30

This is not the effect we want, so when we want to copy a new object, we need to make a deep copy

Using JSON classes

Is to convert an object into a JSON string and return to the JSON object

let a = {
    age: 20
};

let b = JSON.parse(JSON.stringify(a));

b.age = 30;

console.log(a.age); // 20

Advantages: the advantages are convenient and fast, and the performance is relatively good

Disadvantages: however, complex objects may lose properties during JSON conversion, as shown in the following code

let a = {
    age: 20,
    local: function() {
        return 5;
    }
};

let b = JSON.parse(JSON.stringify(a));

console.log(b); // { age : 20 }
console.log(b.local()); //  b.loacl is not a function

Using recursion

dfs-deep-copy.js

//Depth first traversal
let dfs = data => {
    let newData;

    if (type(data) === 'array') {
        newData = [];
        data.map((item, index) => {
            newData[index] = dfs(item);
        });
    } else if (type(data) === 'object') {
        newData = {};
        Object.keys(data).map(item => {
            newData[item] = dfs(data[item]);
        });
    } else {
        newData = data;
    }

    return newData;
};

//Type dictionary
export let type = data => {
    let dist = {
        '[object Array]': 'array',
        '[object Object]': 'object',
        '[object Number]': 'number',
        '[object Function]': 'function',
        '[object String]': 'string',
        '[object Null]': 'null',
        '[object Undefined]': 'undefined'
    };

    return dist[Object.prototype.toString.call(data)];
};

export default dfs;

index.vue

<script>
import dfs from './dfs-deep-copy.js';

export default {
    mounted() {
        let a = {
            age: 20,
            local: function() {
                return 5;
            }
        };

        let b = dfs(a);
        b.local = function() {
            return 10;
        };

        console.log(b.local()); // 10
        console.log(a.local()); // 5
    }
};
</script>

Advantages: the object conversion is relatively stable and retains the original attributes

Disadvantages: the deeper the object level and the more attributes, the higher the performance consumption

The content / inspiration of the article is drawn from the following content

Recommended Today

Ffmpeg plays RTSP / webcam stream

This article will introduce how ffmpeg plays RTSP / webcam / file streams. The process is as follows: RTSP/Webcam/File > FFmpeg open and decode to BGR/YUV > OpenCV/OpenGL display code:https://github.com/ikuokuo/rt…, sub module RTSP local player Ffmpeg preparation git clone https://github.com/ikuokuo/rtsp-wasm-player.git cd rtsp-wasm-player export MY_ROOT=`pwd` # ffmpeg: https://ffmpeg.org/ git clone –depth 1 -b n4.4 https://git.ffmpeg.org/ffmpeg.git $MY_ROOT/3rdparty/source/ffmpeg […]