In JavaScript, there are several ways to clone (or make a shallow copy of) an object. Here’s a breakdown of different techniques, including shallow and deep cloning:
1. Using Object.assign() (Shallow Clone)
Object.assign() creates a shallow copy by copying all enumerable properties from a source object to a target object.
const obj = { a: 1, b: 2 };
const clone = Object.assign({}, obj);
console.log(clone); // { a: 1, b: 2 }
Note: This only creates a shallow copy, so nested objects or arrays are still referenced by the original object.
2. Using Spread Syntax {...obj} (Shallow Clone)
The spread operator (...) creates a shallow copy of the object.
const obj = { a: 1, b: 2 };
const clone = { ...obj };
console.log(clone); // { a: 1, b: 2 }
Note: Similar to Object.assign(), this is also a shallow copy.
3. Using JSON Serialization (Deep Clone)
Serializing an object to JSON and parsing it back creates a deep copy. However, this approach has limitations: it doesn’t work for objects with functions, undefined, Symbol properties, or non-JSON data types like Date and Set.
const obj = { a: 1, b: { c: 2 } };
const deepClone = JSON.parse(JSON.stringify(obj));
console.log(deepClone); // { a: 1, b: { c: 2 } }
Limitation Example:
const obj = { a: 1, b: new Date() };
const deepClone = JSON.parse(JSON.stringify(obj));
console.log(deepClone.b); // String, not a Date object
4. Using structuredClone() (Deep Clone, Modern)
structuredClone() is a modern built-in function that performs a deep clone and handles complex types like Date, RegExp, and circular references.
const obj = { a: 1, b: { c: 2 }, d: new Date() };
const deepClone = structuredClone(obj);
console.log(deepClone); // { a: 1, b: { c: 2 }, d: Date }
Note: structuredClone() is available in modern browsers and Node.js 17+.
5. Using a Recursive Function (Deep Clone)
For a custom deep clone, a recursive function can be used to copy properties, including nested objects.
function deepClone(obj) {
if (obj === null || typeof obj !== 'object') return obj;
const clone = Array.isArray(obj) ? [] : {};
for (const key in obj) {
clone[key] = deepClone(obj[key]);
}
return clone;
}
const obj = { a: 1, b: { c: 2 } };
const clone = deepClone(obj);
console.log(clone); // { a: 1, b: { c: 2 } }
Note: This example handles nested objects and arrays but doesn’t handle edge cases like Date and RegExp types.
6. Using Lodash or Other Libraries (Deep Clone)
Libraries like Lodash offer reliable deep cloning functions. For example, using Lodash’s cloneDeep():
const _ = require('lodash');
const obj = { a: 1, b: { c: 2 } };
const deepClone = _.cloneDeep(obj);
console.log(deepClone); // { a: 1, b: { c: 2 } }
Summary
- Shallow Clone: Object.assign(), { ...obj }
- Deep Clone: JSON.parse(JSON.stringify(obj), structuredClone(), recursive function, _.cloneDeep()
No comments:
Post a Comment