Cloning the Javascript object

Javascript keep the same reference for original and cloned objects, so when you change anything in original object it will change in cloned object also and vice versa. So we can’t simply copy one object to another. Below i have copied each property of original object to cloned using recursive approach.

/**
 * Created by gyaneshwar
 * Date: 29/3/15
 * Time: 11:38 AM
 * To change this template use File | Settings | File Templates.
 */

var jsonObj = {
    "name":"gyani",
    "address":"Bangalore India",
    "occupation":"Software Engineer",
    "url":"gyaneshwarpardhi.wordpress.com",
    "friends":[
        {
            "name":"gyani",
            "address":"bangalore",
            "occupation":"Software Engineer",
            "url":"gyaneshwarpardhi.wordpress.com"

        },

        {
            "name":"gyani",
            "address":"Bangalore India",
            "occupation":"Software Engineer",
            "url":"gyaneshwarpardhi.wordpress.com"

        }
    ],
   "contacts":{
      'email':"gyaan1334@gmail.com",
       "skype":"gyaan1334"

   }
}

var jsonObj2={};

copyFromOneJsonToAnotherJson(jsonObj,jsonObj2);

jsonObj.name="hello changed name";

console.log(jsonObj);

//dude this is not assigned by reference  so jsonObj2 will be as it is
console.log(jsonObj2);

//function to copy one json object to anther
function copyFromOneJsonToAnotherJson(fromJson,toJson){

    for(var key in fromJson){

        if(fromJson.hasOwnProperty(key)){

            if(Array.isArray(fromJson[key])){

                if(fromJson[key] instanceof Array){
                    toJson[key]=[];
                }
                else{
                    toJson[key]={};
                }

                toJson[key]=copyFromOneJsonToAnotherJson(fromJson[key],toJson[key]);

            }
            else{
                toJson[key]=fromJson[key];
            }
        }
    }

    return toJson;
}

A Developer
Gy@n!

About Gyaneshwar Pardhi

Exploring the world and trying to know how can i involve to make this perfect. Gy@n!
This entry was posted in interview Question, javascript, Programming and tagged , . Bookmark the permalink.

Leave a comment