How to clone an object using JavaScript?

We can clone an array using this method:

  1. This is the JavaScript method:
    function clone(obj) {
       if(obj == null || typeof(obj) != 'object')
         return obj;
    
       var temp = {}; // changed
    
       for(var key in obj) {
         if(obj.hasOwnProperty(key)) {
           temp[key] = clone(obj[key]);
         }
       }
       return temp;
    }
  2. How to use it:
    var newObjList = [];
    for(var i=0; i< objList.length; i++){
        newObjList[i] = clone(objList[i]);
    };

Reference link: http://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-clone-an-object

Advertisements