본문 바로가기
프로그램개발/ClientSide(JavaScript,Angular,Vue)

Javascript 객체 복사 (Cloning a Javascript Object)

by 크레도스 2015. 6. 11.

Javascript는 value 타입의 변수들의 경우 별개의 메모리 공간에 생성되지만 객체인 경우에는 reference타입이라 참조 복사가 된다.

복사 처리를 해주려면 그 객체가 가지고 있는 모든 property를 하나 하나 복사하고 상속 구조도 고려하여 복사 처리를 해줘야 된다.


http://stackoverflow.com/questions/728360/copying-an-object-in-javascript


위 Q&A 사이트에 많은 방법들이 나와 있는데 두가지만 언급한다.


첫번째 방법 : 

function clone(obj){
   
var clonedObjectsArray = [];
   
var originalObjectsArray = []; //used to remove the unique ids when finished
   
var next_objid = 0;

   
function objectId(obj) {
       
if (obj == null) return null;
       
if (obj.__obj_id == undefined){
            obj
.__obj_id = next_objid++;
            originalObjectsArray
[obj.__obj_id] = obj;
       
}
       
return obj.__obj_id;
   
}

   
function cloneRecursive(obj) {
       
if (null == obj || typeof obj == "string" || typeof obj == "number" || typeof obj == "boolean") return obj;

       
// Handle Date
       
if (obj instanceof Date) {
           
var copy = new Date();
            copy
.setTime(obj.getTime());
           
return copy;
       
}

       
// Handle Array
       
if (obj instanceof Array) {
           
var copy = [];
           
for (var i = 0; i < obj.length; ++i) {
                copy
[i] = cloneRecursive(obj[i]);
           
}
           
return copy;
       
}

       
// Handle Object
       
if (obj instanceof Object) {
           
if (clonedObjectsArray[objectId(obj)] != undefined)
               
return clonedObjectsArray[objectId(obj)];

           
var copy;
           
if (obj instanceof Function)//Handle Function
                copy
= function(){return obj.apply(this, arguments);};
           
else
                copy
= {};

            clonedObjectsArray
[objectId(obj)] = copy;

           
for (var attr in obj)
               
if (attr != "__obj_id" && obj.hasOwnProperty(attr))
                    copy
[attr] = cloneRecursive(obj[attr]);                

           
return copy;
       
}      


       
throw new Error("Unable to copy obj! Its type isn't supported.");
   
}
   
var cloneObj = cloneRecursive(obj);



   
//remove the unique ids
   
for (var i = 0; i < originalObjectsArray.length; i++)
   
{
       
delete originalObjectsArray[i].__obj_id;
   
};

   
return cloneObj;
}


두번째 방법 : 

function ObjectCopy(obj)

{

 return JSON.parse(JSON.stringify(obj));

}

위 방법은 json.org 사이트의 json2.js를 include 해줘야 한다. (퍼포먼스 측면에서 느릴수 있음.)