In JavaScript, objects are used to store and manipulate collections of data. When working with objects, it is often necessary to create copies or clones of them. Cloning an object is the process of creating a new object that has the same properties and values as the original object, but is a separate object in memory.
Cloning objects can be useful in situations where you want to modify or manipulate a copy of an object without affecting the original object. For example, if you need to update an object in a specific way for a particular operation, you can clone the original object, perform the operation on the clone, and then discard the clone once you are done.
Different methods to clone object in JavaScript
There are several methods available in JavaScript that can be used to clone an object. Some of the most common methods are:
- Using the spread operator (...)
- Using
Object.assign()
- Using
JSON.parse()
andJSON.stringify()
- Using the
Object.create()
method - Using the
lodash clone()
method - Using the
jQuery extend()
method - Using the
npm clone()
package
Method-1: Using spread operator (…
)
We can use the spread operator (...
) to clone an object. This method creates a shallow copy of the object, which means that any nested objects or arrays are still references to the original objects or arrays.
In the code snippet below, we create an original object called originalBlog
that has properties such as name
, authors
, lang
, tools
, and year
. Then, we use the spread operator to create a new object called clonedBlog
, which is a shallow copy of originalBlog
.
const originalBlog = {
name: "GoLinux",
authors: ["Deepak", "Femi"],
lang: ["javascript", "golang"],
tools: ["linux", "docker"],
year: 2019,
};
const clonedBlog = { ...originalBlog };
console.log(clonedBlog);
The output of the code snippet above is:
{
name: 'GoLinux',
authors: [ 'Deepak', 'Femi' ],
lang: [ 'javascript', 'golang' ],
tools: [ 'linux', 'docker' ],
year: 2019
}
Method-2: Using for...in
loop
Another approach to cloning an object is by using a for...in
loop to iterate over the original object's properties and copy them to a new object. This method is the most verbose of all the methods, but it provides the most control over the cloning process. However, it can be limiting depending on the object structure.
In the code snippet below, we create an original object called originalObject
that has properties such as type
, tyres
, model
, and year
. Then, we use a for...in
loop to create a new object called clonedObject
, which is a copy of originalObject
.
const originalObject = {
type: "van",
tyres: 4,
model: "nissan",
year: 2019,
};
const clonedObject = {};
for (let key in originalObject) {
clonedObject[key] = originalObject[key];
}
console.log(clonedObject);
Output
{ type: 'van', tyres: 4, model: 'nissan', year: 2019 }
This method is the most verbose of all the methods, but it provides the most control over the cloning process. However, it can be limiting depending on the object structure. Furthermore, it can quickly become complex when it comes to the iterations and structure.
Method-3: Using the Object.assign()
Object.assign()
can also be used to clone an object. Like the spread operator, this method creates a shallow copy of the object.
In the code snippet below, we create an original object called originalObject
that has properties such as type
, condition
, series
, and age
. Then, we use the Object.assign()
method to create a new object called clonedObject
, which is a copy of originalObject
.
const originalObject = {
type: "main",
condition: false,
series: [13, 17, 19],
age: 30,
};
const clonedObject = Object.assign({}, originalObject);
console.log(clonedObject);
Output
{ type: 'main', condition: false, series: [ 13, 17, 19 ], age: 30 }
Method-4: Using Object.create()
We can also use Object.create()
to clone an object. This method creates a new object with the same prototype as the original object and copies over all of the original object's properties.
const originalObject = {
type: "main",
condition: false,
series: [13, 17, 19],
age: 30,
};
const clonedObject = Object.create(
Object.getPrototypeOf(originalObject),
Object.getOwnPropertyDescriptors(originalObject)
);
console.log(clonedObject);
Output
{ type: 'main', condition: false, series: [ 13, 17, 19 ], age: 30 }
In the above code, Object.create()
creates a new object with the same prototype as the originalObject
and copies over all of its properties, thus creating a cloned object. The output shows that the cloned object is identical to the original object.
Method-5: Using JSON.parse()
and JSON.stringify()
The JSON.parse()
and JSON.stringify()
method is another way to create a copy of an object in JavaScript. This method creates a deep copy of the original object, which means that all the properties and nested objects or arrays are also copied.
The JSON.stringify()
method converts the original object into a JSON string, which can then be parsed into a new object using the JSON.parse()
method. This new object is a clone of the original object and does not reference the original object in any way.
Here's an example of how to clone an object using JSON.parse()
and JSON.stringify()
:
const originalObject = {
type: "main",
condition: false,
series: [13, 17, 19],
age: 30,
};
const clonedObject = JSON.parse(JSON.stringify(originalObject));
console.log(clonedObject);
Output
{ type: 'main', condition: false, series: [ 13, 17, 19 ], age: 30 }
In this code, we first define an originalObject
with some properties, including a nested array called series
. We then create a clonedObject
using the JSON.parse()
and JSON.stringify()
methods.
The JSON.stringify(originalObject)
method converts the originalObject
into a JSON string that looks like this:
'{"type":"main","condition":false,"series":[13,17,19],"age":30}'
The JSON.parse()
method then takes this JSON string and parses it back into a new object, which is assigned to the clonedObject
variable.
However, there are some caveats with this method. Any functions, undefined properties, or properties with circular references will not be included in the cloned object.
Method-6: Using the npm clone() package
The npm clone()
package is a third-party library that can be used to clone objects in JavaScript. It provides a simple and efficient way to create deep copies of objects with nested properties and values.
To use the clone()
package, you need to first install it using npm. You can do this by running the following command in your terminal:
npm install clone
After installing the package, you can use the clone()
method to create a deep copy of an object. Here's an example:
const clone = require('clone');
const originalObj = {
name: "John",
age: 30,
address: {
city: "New York",
state: "NY"
}
};
const clonedObj = clone(originalObj);
console.log(originalObj === clonedObj); // Output: false
console.log(originalObj.address === clonedObj.address); // Output: false
In this example, we first import the clone()
method from the "clone" package using the require()
function. We then create an original object "originalObj
" that contains nested properties and values.
Next, we use the clone()
method to create a deep copy of the original object and assign it to a new variable "clonedObj". We then use console.log()
to compare the two objects, and see that they are not the same object in memory (i.e., "originalObj === clonedObj
" returns false
).
Finally, we use console.log()
to compare the nested "address
" property of the two objects, and see that they are also not the same object in memory.
Method-7: Using the lodash clone()
The lodash clone()
method is a popular third-party library for cloning objects in JavaScript. It provides a simple and efficient way to create shallow and deep copies of objects.
To use the lodash clone()
method, you need to first install the lodash library using npm. You can do this by running the following command in your terminal:
npm install lodash
After installing the library, you can use the clone()
method to create a shallow copy of an object. Here's an example:
const _ = require('lodash');
const originalObj = {
name: "John",
age: 30,
address: {
city: "New York",
state: "NY"
}
};
const clonedObj = _.clone(originalObj);
console.log(originalObj === clonedObj); // Output: false
console.log(originalObj.address === clonedObj.address); // Output: true
Summary
In this article, we've discussed five different ways to clone objects in JavaScript: using the spread operator, using a for...in
loop, using Object.assign()
, using Object.create()
, and using JSON.parse()
and JSON.stringify()
. Each method has its own advantages and disadvantages, and the choice of which method to use will depend on the specific requirements of the project.
It's worth noting that some of these methods create shallow copies of the original object, while others create deep copies. Additionally, some methods may not be able to clone all properties of an object, such as functions or properties with circular references.
References
Spread syntax (...) - JavaScript | MDN (mozilla.org)
for...in - JavaScript | MDN (mozilla.org)
Object.assign() - JavaScript | MDN (mozilla.org)
Object.create() - JavaScript | MDN (mozilla.org)
JSON.parse() - JavaScript | MDN (mozilla.org)
JSON.stringify() - JavaScript | MDN (mozilla.org)