Table of Contents
Primitive Value
Reference Value
Array
Object
JSON.parse(JSON.stringify(obj))
Deep Copy
Home Web Front-end JS Tutorial Learn how to merge and clone objects in JavaScript in one article

Learn how to merge and clone objects in JavaScript in one article

Jun 04, 2021 am 10:39 AM
javascript

This article will introduce you to the methods of merging and cloning objects in JavaScript. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

Learn how to merge and clone objects in JavaScript in one article

Original and reference values ​​(objects) behave very differently when we want to copy them.

Primitive Value

We assume a variable name has a primitive value associated with it (number, string, boolean, undefined and null) . If we copy this variable name to another variable name2 , any modifications to the original variable will not affect the second variable since they are original values.

1

2

3

4

5

let name="前端小智";

let name2= name;

console.log (name, name2); // 前端小智, 前端小智

name="王大冶";

console.log (name,name2); // 王大冶 前端小智

Copy after login

Reference Value

But if we do the same with a reference type value, any changes we make to one variable will also be reflected in the other in a variable because both variables point to the same object.

Array

To copy an array, the slice() method is used to create a new copy of the array. This copy can be modified independently without affecting the original array.

If no arguments are passed, it makes an exact copy of the array, but numbers can also be passed as arguments. If only one number is passed, it will determine the value of the index from which we want to copy, while if two numbers are passed, it will mark the start and end.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

// 示例1

const names = ['前端小智', '王大冶', '小力'];

const names2 = names;

console.log(names, names2);

// ["前端小智", "王大冶", "小力"]

// ["前端小智", "王大冶", "小力"]

 

// 示例2

names2[2] = '前端小力';

console.log(names, names2);

//  ["前端小智", "王大冶", "前端小力"]

//  ["前端小智", "王大冶", "前端小力"]

 

// 示例3

const name2 = names.slice();

names[2] = '我是隔壁老智';

console.log(name2, names2)

// ["前端小智", "王大冶", "前端小力"]

//  ["前端小智", "王大冶", "我是隔壁老智"]

Copy after login

Object

The same happens when the reference value is an object, and any modification to one of its properties will affect both variables. To clone an object, use the Object.assign() method, which copies the values ​​of all enumerable properties of one or more source objects to the target object, but this method only copies the values ​​of the object's A shallow copy.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

// 示例1

const names = {

  name: '前端小智',

  surname: '隔壁老智'

}

 

const names2 = names;

console.log(names, names2) // 打印结果是一模一样的

 

// 示例2

names2.surname ='隔壁老王';

console.log(names, names2)

 

// {name: "前端小智", surname: "隔壁老王"}

// {name: "前端小智", surname: "隔壁老王"}

 

// 示例3

const names3 = Object.assign({}, names);

names3.surname = '隔壁老色P';

console.log(names, names3)

 

// {name: "前端小智", surname: "隔壁老王"}

// {name: "前端小智", surname: "隔壁老色P"}

Copy after login

To make a deep copy of an object, you need to use other methods.

As we said, the Object.assign() method only works as a shallow copy (i.e. when our object has no other objects as properties). In these cases, a deep copy of the object must be made.

Unlike shallow copy, deep copy copies each child object recursively until all involved objects have been copied.

What methods can we use to make a deep copy of an object?

JSON.parse(JSON.stringify(obj))

This method uses JSON.stringify() to convert the object to a string, Then use JSON.parse() to convert it back to an object. This method works for simple objects, but not if the object properties are functions.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

const names = {

  name: '前端小智',

  surname: '隔壁老智',

  social: {

    wx: '大迁世界',

    url: 'www.lsp.com'

  }

}

const names2 = JSON.parse(JSON.stringify(names));

names2.social.url = 'www.baidu.com';

console.log(names, names2);

 

/**

{

  name: "前端小智"

  social: {wx: "大迁世界", url: "www.lsp.com"}

  surname: "隔壁老智"

}

*/

 

/**

{

  name: "前端小智"

  social: {wx: "大迁世界", url: "www.baidu.com"}

  surname: "隔壁老智"

}

*/

Copy after login

Deep Copy

Another very interesting and elegant way to deep copy objects is to use recursive functions.

We create a deepClone(object) function and pass it the object we want to clone as a parameter. Inside the function, a local variable clone will be created, which is an empty object in which every property that will be cloned from the starting object will be added to it.

Specific ideas:

  • If the property is not an object, simply clone it and add it to the new cloned object.
  • If the property is an object, execute the deepClone(value) function again and pass the value of the property (object in this case) as parameter and repeat the same process.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

function deepClone(object) {

  var clone = {};

  for (var key in object) {

    var value = object[key];

    if (typeof(value) !== 'object') {

      clone[key] = value;

    } else {

      clone[key]=deepClone(value);

    }

  }

  return clone;

}

 

deepClone({value1:1,value2:{value3:2}});

//{value1:1,value2:{value3:2}}

deepClone({value1:1,value2:{value3:{value3b:3}}});

//{value1:1,value2:{value3:{value3b:3}}}

Copy after login

English original address: https://www.ma-o.org/en/programming/javascript/the-javascript-asign-method-to-merge-and-clone -objects

Author: Luigi Nori

Translator: Front-end Xiaozhi

For more programming-related knowledge, please visit: Programming Video ! !

The above is the detailed content of Learn how to merge and clone objects in JavaScript in one article. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1657
14
PHP Tutorial
1257
29
C# Tutorial
1230
24
How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

See all articles