cloning objects

8 0 0
                                        

cloning objects - this is the same as creating a second object but empty and then put all the properties of the first object here in this second object. 

let firstObj = {

    prop1: "apple",

   prop2: "banana"

};

let secondObj = {};

//Syntax 1: Normally, you used a for each loop to iterate your first object and assign each //property to the second object to copy it.

for(elem in firstObj){

    secondObj[elem] = firstObj[elem];

}

//Syntax 2: Or you can just assign first object to second object.

secondObj = firstObj;

//Syntax 3:  You can use an Object.assign(targetObject, sourceObject...) method.

Object.assign(secondObj, firstObj);

===================

let x = {

         name: "Bucky roberts",

         age: 27,

        gender: "male",

        anotherX: {             

                occupation: "student",

                address: "new york",             

                mail: "your mail",             

                 phone: "68574930"      

         }

};

let y = {};

let z = {};

let w = {};

function displayItAllHere(){

       isObjectAndCopy();     

       displayY();

}

function isObjectAndCopy(){

        for(elem in x){

               if(typeof x[elem] == 'object'){

                     Object.assign(w, x[elem]);

               }else{               

                     z[elem] = x[elem];          

               }  

        }     

        Object.assign(y, z, w);

}


function displayY(){

     for(index in y){

          document.writeln('${index}: ${y[index]}');

     }

}

=================

HTML

displayItAllHere()

Result:

name: Bucky roberts age: 27 gender: male occupation: student address: new york mail: your mail phone: 68574930

Javascript ProgrammingWhere stories live. Discover now