To clone a JavaScript object, you can use the following methods:
- Shallow Copy:
- Spread Operator (
...
):This method creates a shallow copy, meaning nested objects or arrays within the original object are still referenced, not duplicated.
Object.assign()
Method:Like the spread operator, this also performs a shallow copy.
- Spread Operator (
- Deep Copy:
structuredClone()
Function:This built-in function creates a deep copy of the object, duplicating all nested structures. However, it’s not supported in all environments.
- JSON Serialization:
This approach creates a deep copy but has limitations: it doesn’t support functions, symbols,
undefined
, or objects with circular references.
For complex objects or those containing non-serializable properties, consider using libraries like Lodash’s _.cloneDeep()
method to ensure accurate deep cloning.