How to Clone an Object in JavaScript (without reference)
In this tutorial, we are going to learn about two different solutions to copy an object in JavaScript with the help of examples.
Object.assign method
The Object.assign()
method is used to copy all enumerable values from a source object to the target object.
Example:
const obj = {a:1,b:2,c:3};
const clone = Object.assign({},obj);
console.log(clone); // {a:1,b:2,c:3};
In the above code, we have passed two arguments to the Object.assign()
method the first one is target object
and the second one is source object
.
Spread Operator (…)
In es6, we have spread operator
which is also used to clone an object.
const obj = {a:1,b:2,c:3};
const clone = {...obj};
console.log(clone); // {a:1,b:2,c:3};
Note: These above two methods are only used for shallow copying of objects but not for deep copying.
Shallow copying vs Deep copying
Shallow copying means it only copies the normal object values but nested values still use the reference to an original object.
Example: We are using the spread operator to shallow clone an object.
const obj = {a:1,b:2,c:{d:3}};
const shallowClone = {...obj};
obj.c.d = 34; // updates the d property value
console.log(obj); // {a:1,b:2,c:{d:34}}
console.log(shallowClone); // {a:1,b:2,c:{d:34}}
In the above code, we have updated the obj.c.d
property value to 34
but our shallowClone.c.d
property value is also updated because it’s still holding the reference to an original object obj
.
Deep copying an Object
To deep copy an object we need to use JSON.parse()
and JSON.stringify()
methods.
Example:
const obj = {a:1,b:2,c:{d:3}};
const deepClone = JSON.parse(JSON.stringify(obj));
Now if we change obj.c.d
property value the deepClone
object property value remains unchanged because there is no reference to the original object.
obj.c.d = 35;
// d value is changed
console.log(obj); // {a:1,b:2,c:{d:35}}
// d value remains unchanged because there is no reference
console.log(deepClone); // {a:1,b:2,c:{d:3}}