Cloning
Cloning in javascript is nothing but copying an object properties to another object so as to avoid creation of an object that already exists.
There are a few ways to clone a javascript object.
1) Iterating through each property and copy them to a new object.
2) Using JSON method.
3) Using object.assign() method.
Let's discuss each method individually
a) Iterating through each property and copy them to a new object.
This is an old method to clone a javascript object in which each property will be iterated and copied to a new object.It's a simple method but seldom it is used.
Example
<html> <body> <p id="cloning-1"></p> <script> const sourceObject = {name:"salman", age:23, salary:25000}; let requiredObj = {}; for (let pro in sourceObject) { if (sourceObject.hasOwnProperty(pro)) { requiredObj[pro] = sourceObject[pro]; } } document.getElementById("cloning-1").innerHTML = "targetObject name = "+requiredObj.name+", age = " + requiredObj.age+", salary = "+requiredObj.salary; </script> </body> </html>
Output
targetObject name = salman, age = 23, salary = 25000
b) JSON method
It is one of the modern methods to clone a JavaScript object.In this method, source object must be JSON safe.
Example
<html> <body> <p id="cloning-2"></p> <script> const sourceObject = {name:"salman", age:23, salary:25000}; let requiredObj = {}; requiredObj = JSON.parse(JSON.stringify(sourceObject)); document.getElementById("cloning-2").innerHTML = "targetObject name = "+requiredObj.name+", age = " + requiredObj.age+", salary = "+requiredObj.salary; </script> </body> </html>
Output
targetObject name = salman, age = 23, salary = 25000
c) Object.assign()
This is an advanced method used very frequently now a days to clone javascript objects.This method does only shallow copy which means that nested properties are still copied by reference.
Example
<html> <body> <p id="cloning-3"></p> <script> const sourceObject = {name:"salman", age:23, salary:25000}; let requiredObj = {}; requiredObj = Object.assign({}, sourceObject); document.getElementById("cloning-3").innerHTML = "targetObject name = "+requiredObj.name+", age = " + requiredObj.age+",salary"+requiredObj.salary; </script> </body> </html>
Output
targetObject name = salman, age = 23, salary = 25000