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 formatted data - Cannot handle object types such as functions, RegExp, Date, etc. - Cannot handle cases where there are circular references in the objectUsage:
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 obviously assumes that you have already imported the lodash library.
Using the deepmerge library (for React and Vue)
deepmerge is a library for frontend frameworks like React and Vue, which 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 frontend frameworks like React and Vue, using a library is a more convenient choice.