Home > Web Front-end > JS Tutorial > How to Create a True Deep Copy of a JavaScript Object?

How to Create a True Deep Copy of a JavaScript Object?

Patricia Arquette
Release: 2024-12-26 02:03:10
Original
750 people have browsed it

How to Create a True Deep Copy of a JavaScript Object?

How to Clone JavaScript Objects Correctly

Cloning JavaScript objects is a crucial task in various programming scenarios. However, creating a copy of an object that remains unaffected by changes made to the original can be challenging due to the complexities of JavaScript's object system.

Pitfalls of Native Copying Methods

JavaScript's native object assignment operator (e.g., x = y) only creates a reference to the original object. Changes made to either x or y will affect both objects. Additionally, copying objects derived from built-in JavaScript objects (e.g., Array, Date) can introduce unwanted properties.

Comprehensive Cloning Solution

To create a deep copy of a JavaScript object, consider the following comprehensive solution:

function clone(obj) {
  if (null == obj || "object" != typeof obj) return obj;

  var copy = obj.constructor();
  for (var attr in obj) {
    if (obj.hasOwnProperty(attr)) copy[attr] = clone(obj[attr]);
  }
  return copy;
}
Copy after login

This function employs a recursive approach to traverse the object's properties and create a new object with separate instances for each property value. It handles the cases of null, undefined, and various built-in object types while excluding non-enumerable and hidden properties.

Edge Cases and Assumptions

While the solution covers most scenarios, it assumes that the object data forms a tree structure, meaning there are no circular references within the object. Also, it requires knowledge of the object's constructor to properly instantiate the cloned object.

Structured Cloning (ES2022 Update)

In modern browsers, the structured cloning standard provides a more robust and efficient way to create deep copies of objects. The structuredClone() function clones the object in its entirety, preserving hidden properties and circular references.

const clone = structuredClone(object);
Copy after login

Remember, cloning objects can be a complex task, and consider the limitations of each approach based on the specific requirements of your application.

The above is the detailed content of How to Create a True Deep Copy of a JavaScript Object?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template