Table of Contents
Operator
Object.assign()
Deep copyJSON.parse(JSON.stringify())
Use the expansion operator [... ]
Invent your own wheel:
Home Web Front-end JS Tutorial In-depth analysis of object copy methods in JavaScript (with code)

In-depth analysis of object copy methods in JavaScript (with code)

Aug 20, 2021 am 09:55 AM
java js

In the previous article "What you need to know about the use of JavaScript "jquery inheritance" (detailed code explanation)", we learned about the use of JavaScript "jquery inheritance". The following article will introduce you to the object copy method in JS. Friends in need can refer to it.

In-depth analysis of object copy methods in JavaScript (with code)

When it comes to object copying in javascript, the first thing we think of is Object.assign()

JSON.parse(JSON.stringify()),and ES6’s expansion operator [...]

Because in js=operator cannot create a copy for an object, it is just a reference to the object

Operator

var x = {
  a: 1,
  b: 2,
};
y = x;
x.a = 10;
console.log(x); //{a:10, b:2}
console.log(y); //{a:10, b:2}
Copy after login

Therefore, when performing object operations, the equal operator (=) is not advisable

Object.assign()

var x = {
  a: 1,
  b: 2,
};
y = Object.assign({}, x);
x.a = 10;
console.log(x); //{a:10, b:2}
console.log(y); //{a:1, b:2}
Copy after login

At first glance, it is not An exception will be found, because what we want is the result we want. If we make the object structure a little more complicated and look at it

var x = {
  a: 1,
  b: 2,
  c: {
    d: 3,
  },
};
y = Object.assign({}, x);

x.a = 5;
console.log(x); //{a:5, b:2, c:{d:3}}
console.log(y); //{a:5, b:2, c:{d:3}}

x.c.d = 10;
console.log(x); //{a:5, b:2, c:{d:10}}
console.log(y); //{a:5, b:2, c:{d:10}}
Copy after login

, we will find a pitfall at this time, then it has been provedObject.assign()Only implements a shallow copy of the object

Object.assign()Another thing to note is that non-enumerable objects with attributes on the prototype chain cannot be copied. Take a look at the code. :

var x = {
  a: 1,
};
var y = Object.create(x, {
  b: {
    value: 2,
  },
  c: {
    value: 3,
    enumerable: true,
  },
});
var z = Object.assign({}, y);
console.log(z); //{c:3}
Copy after login

is surprising to get the value of z, because x is the prototype chain of y, so x Will not be copied

Attributeb is a non-enumerable property and will not be copied

Only c has an enumerable description, he can be Enumeration, so it can be copied

The above pitfalls can also be solved very well, and look down:

Deep copyJSON.parse(JSON.stringify())

Solution to the pitfalls of shallow copy

var x = {
  a: 1,
  b: 2,
  c: {
    d: 3,
  },
};
y = JSON.parse(JSON.stringify(x));
x.a = 5;
x.c.d = 10;
console.log(x); //{a:5, b:2, c:{d:10}}
console.log(y); //{a:1, b:2, c:{d:3}}
Copy after login

Of course, for ordinary objects, this copying method is basically perfect, so where is its pitfall

var x = {
  a: 1,
  b: function b() {
    return "2";
  },
};
y = JSON.parse(JSON.stringify(x));
z = Object.assign({}, x);

console.log(y); //{a:1}
console.log(z); //{a:1, b:function b(){return '2'}}
Copy after login

From the results, Object.assign() can copy the method, JSON.parse(JSON.stringify()) cannot

Let’s look at the second one A pitfall:

var x = {
  a: 1,
  b: {
    c: 2,
    d: 3,
  },
};

x.c = x.b;
x.d = x.a;
x.b.c = x.c;
x.b.d = x.d;

var y = JSON.parse(JSON.stringify(x));
console.log(x);

/*
Uncaught TypeError: Converting circular structure to JSON

    at JSON.stringify (<anonymous>)
    at <anonymous>:8:25

*/
Copy after login

reported an error, and the result shows that JSON.parse(JSON.stringify()),cannot copy the circular reference object

Let’s take a look Object.assign()

var x = {
  a: 1,
  b: {
    c: 2,
    d: 3,
  },
};

x.c = x.b;
x.d = x.a;
x.b.c = x.c;
x.b.d = x.d;

var y = Object.assign({}, x);
console.log(x);
/*
[object Object]{
a:1, 
b:[object, Object], 
d:[object, Object], 
d:1
}
*/
Copy after login

Use the expansion operator [... ]

The expansion operator for object literals is currently ECMAScript's Phase 3 proposal makes copying objects simpler

var x = [
  "a",
  "b",
  "c",
  "d",
  {
    e: 1,
  },
];
var y = [...x];
console.log(y); //[&#39;a&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;, {&#39;e&#39;:1}]

var m = {
  a: 1,
  b: 2,
  c: ["d", "e"],
};
var n = {
  ...m,
};
console.log(n); //{a:1, b:2, c:[&#39;d&#39;, &#39;e&#39;]}
Copy after login

It should be noted that the spread operator is also a shallow copy. So is it really so difficult to copy objects?

Invent your own wheel:

function copy(x) {
  var y = {};
  for (m in x) {
    y[m] = x[m];
  }
  return y;
}
var o = {
  a: 1,
  b: 2,
  c: {
    d: 3,
    e: 4,
  },
};
var p = copy(o);
Copy after login

Some people say that there shouldn’t be much problem if you do this. Then we can only laugh and keep going

var x = {};

Object.defineProperty(x, "m", {
  value: 5,
  writable: false,
});

console.log(x.m); //5
x.m = 25; //这一步没报错,但是也没执行
console.log(x.m); //5
Copy after login

In this way, the expansion operator will also encounter pitfalls when copying objects here.

There are pitfalls everywhere, and it’s hard to guard against them.... As I write this, I guess there are still many pitfalls that haven’t been fully listed.

I’ll write more later

[End]

Recommended learning: JavaScript video tutorial

The above is the detailed content of In-depth analysis of object copy methods in JavaScript (with code). 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)

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

See all articles