What are the different ways to copy an object or an array?
TL;DR
To copy an object or an array in JavaScript, you can use several methods. For shallow copies, you can use the spread operator (...
) or Object.assign()
. For deep copies, you can use JSON.parse(JSON.stringify())
or libraries like Lodash's _.cloneDeep()
.
Different ways to copy an object or an array
Shallow copy
Using the spread operator
The spread operator (...
) is a concise way to create a shallow copy of an array or an object.
Using Object.assign()
Object.assign()
can also be used to create a shallow copy of an object.
Deep copy
Using JSON.parse(JSON.stringify())
This method is a simple way to create a deep copy of an object or an array. However, it has limitations, such as not handling functions, undefined
, or circular references.
Using Lodash's _.cloneDeep()
Lodash is a popular utility library that provides a _.cloneDeep()
method for deep copying objects and arrays.
Other methods
Using recursion
For custom deep copy logic, you can implement a recursive function.