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()
.
// Shallow copy of an array
const originalArray = [1, 2, 3];
const shallowCopyArray = [...originalArray];
// Shallow copy of an object
const originalObject = { a: 1, b: 2 };
const shallowCopyObject = { ...originalObject };
// Deep copy using JSON methods
const deepCopyObject = JSON.parse(JSON.stringify(originalObject));
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.
// Shallow copy of an array
const originalArray = [1, 2, 3];
const shallowCopyArray = [...originalArray];
// Shallow copy of an object
const originalObject = { a: 1, b: 2 };
const shallowCopyObject = { ...originalObject };
Using Object.assign()
Object.assign()
can also be used to create a shallow copy of an object.
const originalObject = { a: 1, b: 2 };
const shallowCopyObject = Object.assign({}, originalObject);
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.
const originalObject = { a: 1, b: { c: 2 } };
const deepCopyObject = JSON.parse(JSON.stringify(originalObject));
Using Lodash's _.cloneDeep()
Lodash is a popular utility library that provides a _.cloneDeep()
method for deep copying objects and arrays.
const _ = require('lodash');
const originalObject = { a: 1, b: { c: 2 } };
const deepCopyObject = _.cloneDeep(originalObject);
Other methods
Using recursion
For custom deep copy logic, you can implement a recursive function.
function deepCopy(obj) {
if (obj === null || typeof obj !== 'object') {
return obj;
}
if (Array.isArray(obj)) {
return obj.map((item) => deepCopy(item));
}
const copy = {};
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
copy[key] = deepCopy(obj[key]);
}
}
return copy;
}
const originalObject = { a: 1, b: { c: 2 } };
const deepCopyObject = deepCopy(originalObject);