How to clone an object using spread operator in JavaScript?


Cloning is nothing but copying an object from one variable to another variable. Simple cloning using the assignment operator does not work as per our intentions. When cloning takes place, a change in any variable shouldn't reflect any kind of change in another variable. But in the case of assignment operator, a change in any variable will definitely reflect in another variable. So to reduce this drawback ES6 has provided spread operator

Example

In the following example, cloning is done using the spread operator. So a change in one variable is reflected in another variable.

Live Demo

<html>
<body>
<script>
   var org = {org1 : "Serveneedy", org2 : "Praveenlatha", org3 : "Redcross" };
   document.write(JSON.stringify("without change org :" + " "+ JSON.stringify(org)));
   var neworg = org;
   org.org1 = "gatesfoundation";
   document.write("</br>");
   document.write(JSON.stringify("with change org :" + " "+ JSON.stringify(org)));
   document.write("</br>");
   document.write(JSON.stringify("change also reflected in neworg :" +" "+JSON.stringify(neworg)));
</script>
</body>
</html>

Output

"without change org : {\"org1\":\"Serveneedy\",\"org2\":\"Praveenlatha\",\"org3\":\"Redcross\"}"
"with change org : {\"org1\":\"gatesfoundation\",\"org2\":\"Praveenlatha\",\"org3\":\"Redcross\"}"
"change also reflected in neworg :{\"org1\":\"gatesfoundation\",\"org2\":\"Praveenlatha\",\"org3\":\"Redcross\"}"


Example

In the following example spread operator is used so a change in the original object doesn't reflect in the cloned object.

Live Demo

<html>
<body>
<script>
   var org = {org1 : "Serveneedy", org2 : "Praveenlatha", org3 : "Redcross" };
   document.write(JSON.stringify("without change org :" + " "+ JSON.stringify(org)));
   var neworg = {...org};
   org.org1 = "gatesfoundation";
   document.write("</br>");
   document.write(JSON.stringify("with change org :" + " "+ JSON.stringify(org)));
   document.write("</br>");
   document.write(JSON.stringify("change also reflected in neworg" +" "+JSON.stringify(neworg)));
</script>
</body>
</html>

Output

"without change org : {\"org1\":\"Serveneedy\",\"org2\":\"Praveenlatha\",\"org3\":\"Redcross\"}"
"with change org : {\"org1\":\"gatesfoundation\",\"org2\":\"Praveenlatha\",\"org3\":\"Redcross\"}"
"change also reflected in neworg : {\"org1\":\"Serveneedy\",\"org2\":\"Praveenlatha\",\"org3\":\"Redcross\"}"
raja
Published on 25-Jul-2019 11:57:35
Advertisements