banner
leoking

leoking

前端开发者
tg_channel

How to achieve deep copy in JS.

In JavaScript, deep copy refers to creating a new object with the same property values as the original object, but modifying the property values of the new object will not affect the original object. Shallow copy, on the other hand, creates a new object but only copies the reference of the original object.

Regarding the implementation methods of deep copy, I will provide the following solutions and suggestions:

Using JSON#

JSON.parse() and JSON.stringify() This is the simplest method to achieve deep copy, but it has some limitations: - Only applicable to objects containing simple JSON format data - Cannot handle object types such as functions, RegExp, Date, etc. - Cannot handle cases where there are circular references in the object

Usage:

const deepClone = (obj) => JSON.parse(JSON.stringify(obj));

Recursive implementation of deep copy#

Recursive implementation of deep copy is a more general method that can solve some limitations of the JSON.parse and JSON.stringify methods. The specific implementation is as follows:

function deepClone(obj, hash = new WeakMap()) {
  if (obj === null) return obj;
  if (typeof obj !== 'object') return obj;
  if (obj instanceof RegExp) return new RegExp(obj);
  if (obj instanceof Date) return new Date(obj);

  if (hash.has(obj)) return hash.get(obj);

  const result = new obj.constructor();

  hash.set(obj, result);

  for (let key in obj) {
    if (obj.hasOwnProperty(key)) {
      result[key] = deepClone(obj[key], hash);
    }
  }

  return result;
}

Using lodash's _.cloneDeep() method#

If you are already using the lodash library, you can conveniently use its _.cloneDeep() method to achieve deep copy.

import _ from 'lodash';

const clonedObj = _.cloneDeep(originalObj);

This implementation method is obviously based on the assumption that you have already imported the lodash library.

Using the deepmerge library (for React and Vue)
deepmerge is a library for front-end frameworks like React and Vue that can help you easily perform deep copy.

First, install deepmerge via npm or yarn:

npm install deepmerge

or

yarn add deepmerge

Then import and use it in your code:

import deepmerge from 'deepmerge';

const newObj = deepmerge(obj1, obj2);

There are many ways to implement deep copy, so choose the appropriate method based on your specific situation. If you want a simple solution that can handle circular references, I recommend using the recursive implementation. If you are already using lodash in your project or need to be compatible with front-end frameworks like React and Vue, using a library is a more convenient choice.

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.