Overview
Developers tend to get into a situation where they need to clone an object from a sample object always before processing a particular functionality, which may push us to do some research on different ways available to find out a better option.
In this article, let's look at different ways to clone an object in Javascript or Typescript or Angular.
Content
When do we need to clone?
While coding, sometimes we get into a situation where we need to clone an object from a sample object. In such situations, we need to find out different ways to clone to find out a better option.
We will discuss a few simple ways to clone an object as mentioned below with an example.
Let's take this sample nested object to check the differences between the Shallow clone and Deep clone.
const nestedObject = {
name: 'Arun',
address: {
city: 'Hyderabad',
},
};
Shallow Clone
The shallow clone will clone the object, where the first level is copied and the deeper levels are referenced, which makes the deeper levels of the actual object disturbed when changes are made on the clone object.
It can be done in two ways, wherein both of them the deeper levels are disturbed when they are changed on clone object as shown below.
Using spread
Make a note of the 3 dots before the nested object while creating a clone.
const shallowClone = { ...nestedObject };
shallowClone.name = 'Kumar';
shallowClone.address.city = 'Bangalore';
console.log(nestedObject);
// { name: 'Arun', address: { city: 'Bangalore' } }
console.log(shallowClone);
// { name: 'Kumar', address: { city: 'Bangalore' } }
Using Object.assign()
Make a note of the curly braces in Object.assign({}, nestedObject).
const shallowClone = Object.assign({}, nestedObject);
shallowClone.name = 'Kumar';
shallowClone.address.city = 'Bangalore';
console.log(nestedObject);
// { name: 'Arun', address: { city: 'Bangalore' } }
console.log(shallowClone);
// { name: 'Kumar', address: { city: 'Bangalore' } }
Deep Clone
The deep copy will clone the object completely, where all the levels are copied and none of them are referenced, which makes it a true copy.
It can be done using JSON methods as shown below.
const deepClone = JSON.parse(JSON.stringify(nestedObject));
deepClone.name = 'Kumar';
deepClone.address.city = 'Bangalore';
console.log(nestedObject);
// { name: 'Arun', address: { city: 'Hyderabad' } }
console.log(deepClone);
// { name: 'Kumar', address: { city: 'Bangalore' } }
Which one to use?
If the object is a non-nested object, choose Shallow Clone, which is faster than Deep Clone.
If the object is a nested object, choose Deep Clone, which does a full copy without disturbing the original object.
Conclusion
We know the different ways that can be used to clone an object in javascript.