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

Detailed explanation of two points to note in vue3: setup

Table of contents In vue2 In vue3 Notes on setup ...

Set the width of the table to be fixed so that it does not change with the text

After setting the table width in the page to width...

Vue: Detailed explanation of memory leaks

What is a memory leak? A memory leak means that a...

Detailed steps to build the TypeScript environment and deploy it to VSCode

Table of contents TypeScript environment construc...

HTML+Sass implements HambergurMenu (hamburger menu)

A few days ago, I watched a video of a foreign gu...

Detailed explanation of application scenarios of filters in Vue

filter is generally used to filter certain values...

Vue+js click arrow to switch pictures

This article example shares the specific code of ...

An example of how to write a big sun weather icon in pure CSS

Effect The effect diagram is as follows Implement...

Detailed explanation of VUE Token's invalidation process

Table of contents Target Thought Analysis Code la...

SQL merge operation of query results of tables with different columns

To query two different tables, you need to merge ...

Detailed explanation of web page loading progress bar (recommended)

(When a web page is loading, sometimes there is t...

CSS polar coordinates example code

Preface The project has requirements for charts, ...

How to find the my.ini configuration file in MySQL 5.6 under Windows

Make a note so you can come back and check it lat...

How to install Oracle_11g using Docker

Install Oracle_11g with Docker 1. Pull the oracle...