JS deep and shallow copy details

JS deep and shallow copy details

1. What does shallow copy mean?

A shallow copy is a copy of only the references to the data stored in the stack, without copying the references pointing to the contents in the heap. Shallow copying of multiple data copies multiple references, which point to the same content in the heap. When a shallow copy of data is modified, that is, the content pointed to by the reference in the heap is modified, then other data pointed to here by reference will also change.

let obj = {
    a:1,
    b:2,
    c:{
        c1:10,
        c2:20
    }
}

let objA = obj;
objA.a = 'a';

console.log(obj.a); // 'a'
console.log(objA.a); // 'a'

2. What does deep copy mean?

A deep copy is a copy of the contents of the heap to create a new object. Multiple deep copies will be multiple different objects, which means they have different references and point to different heap contents.

3. Reasons for using deep copy

In normal development, data is sometimes transmitted and received. After receiving the transmitted data, it is inevitable to process and transform the data. In order not to destroy the original data structure, deep copy can be used to copy the data, and then process the generated new data. Deep copying can also prevent the problem of reference confusion after modifying multiple references, reducing the chance of BUG .

4. Several methods for deep copying

Implementation method 1: JSON serialization and deserialization

let obj = {
    a:1,
    b:2,
    c:{
        c1:10,
        c2:20
    }
}

let objA = JSON.parse(JSON.stringify(obj)); //JSON serialization and deserialization objA.a = 'a';

console.log(obj.a); // 1
console.log(objA.a); // 'a'

Although JSON serialization and deserialization can achieve deep copying, there are several disadvantages to note:

  • date object is converted to a date string
  • No access to prototype
  • Unable to copy undefined properties
  • NAN and infinity are converted to NULL
let d1 = new Date();
let obj = {
    d1,
    d2: undefined,
    d3:NaN
}
let objD = JSON.parse(JSON.stringify(obj));
console.log(obj) 
console.log(objD)

Implementation method 2: Object.assign()

let obj = {
    a:1,
    b:2,
    c:{
        c1:10,
        c2:20
    }
}

let objA = Object.assign(obj);
objA.a = 'a';

console.log(obj.a); // 1
console.log(objA.a); // 'a'

Although Object.assign() can achieve deep copying, it only makes shallow copies of deeper object references.

let obj = {
    a:1,
    b:2,
    c:{
        c1:10,
        c2:20
    }
}

let objA = Object.assign(obj);
objA.c.c1 = 'c1'; //Object.assign() is just a deep copy.

console.log(obj.c.c1); // 'c1'
console.log(objA.c.c1); // 'c1'

Implementation method three: extension operator

let obj = {
    a:1,
    b:2,
    c:{
        c1:10,
        c2:20
    }
}

let objA = {...obj};;
objA.a = 'a';

console.log(obj.a); // 1
console.log(objA.a); // 'a'

Although the spread operator " " can achieve deep copying, it only makes shallow copies of deeper object references.

let obj = {
    a:1,
    b:2,
    c:{
        c1:10,
        c2:20
    }
}

let objA = {...obj};
objA.c.c1 = 'c1'; //The extension operator "..." is the same as Object.assign(), which only has one layer of deep copy and cannot have multiple layers of deep copy.

console.log(obj.c.c1); // 'c1'
console.log(objA.c.c1); // 'c1'

Implementation method 4: Using recursion

If you want to achieve deep copying and multi-layer deep copying, you can use recursive loop copying.

let obj = {
    a:1,
    b:2,
    c:{
        c1:10,
        c2:20
    }
}

const ReCopy = function (paramter) {
        let target = null;
        let isObject = paramter.constructor === Object;
        let isArray = paramter.constructor === Array;
        if (isObject || isArray) {
            target = Array.isArray(paramter) ? [] : {};
            for (let i in parameter) {
                target[i] = ReCopy(paramter[i]);
            }
        } else {
            target = parameter;
        }
        return target;
    }

let objA = ReCopy(obj);
objA.c.c1 = 'c1';

console.log(obj.c.c1); // 10
console.log(objA.c.c1); // 'c1'

5. Ladash deep copy

lodash deep copy is a more professional deep copy method.

Install lodash

Initialize first, generate the package.json file, and then install it using the following command.

npm i -S lodash

Import lodash

var _ = require('lodash');

Using lodash

let obj = {
    a:1,
    b:2,
    c:{
        c1:10,
        c2:20
    }
}

let objA = _.cloneDeep(obj);
objA.c.c1 = 'c1'; 

console.log(obj.c.c1); // 10
console.log(objA.c.c1); // 'c1'

This is the end of this detailed article about the deep and shallow copy of JS. For more relevant content about the deep and shallow copy of JS, please search for previous articles on 123WORDPRESS.COM or continue to browse the related articles below. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • JavaScript copy object and Object.assign method cannot achieve deep copy
  • Detailed explanation and example analysis of deep copy in javascript
  • A brief discussion on deep copy in Javascript
  • Improved version of the method to achieve deep copy through Json object
  • Detailed explanation of deep and shallow copying of JavaScript objects

<<:  Introduction to the use of base link tag base

>>:  MySQL account password modification method (summary)

Recommend

10 bad habits to avoid in Docker container applications

There is no doubt that containers have become an ...

How to build Nginx image server with Docker

Preface In general development, images are upload...

How to dynamically add ports to Docker without rebuilding the image

Sometimes you may need to modify or add exposed p...

How to use jconsole to monitor remote Tomcat services

What is JConsole JConsole was introduced in Java ...

Summary of new usage examples of computed in Vue3

The use of computed in vue3. Since vue3 is compat...

Summary of Button's four Click response methods

Button is used quite a lot. Here I have sorted ou...

Markup Language - Anchor

Previous: Markup Language - Phrase Elements Origin...

Basic installation process of mysql5.7.19 under winx64 (details)

1. Download https://dev.mysql.com/downloads/mysql...

JS implements array filtering from simple to multi-condition filtering

Table of contents Single condition single data fi...

Quickly solve the problem of slow and stuck opening of input[type=file]

Why is it that when the input tag type is file an...

W3C Tutorial (1): Understanding W3C

W3C, an organization founded in 1994, aims to unl...

JavaScript to implement a simple clock

This article example shares the specific code for...

MySQL index principle and usage example analysis

This article uses examples to illustrate the prin...