spread 연산자(...)를 사용해도 깊은 복사가 되지 않는다.
중첩 객체의 경우 원본객체에 영향이 간다.
const foo = {
name: 'test',
obj: {
a: 1,
b: 2,
},
};
// 얕은 복사
const bar = { ...foo };
bar.name = 'hth';
bar.obj.a = 3;
console.log(foo); // { name: 'test', obj: { a: 3, b: 2 } }
console.log(bar); // { name: 'hth', obj: { a: 3, b: 2 } }
const a = [
[1, 2],
[3, 4],
[5, 6],
];
// 깊은 복사
const b = JSON.parse(JSON.stringify(a));
b[0][0] = 9;
console.log(a); // [ [ 1, 2 ], [ 3, 4 ], [ 5, 6 ] ]
console.log(b); // [ [ 9, 2 ], [ 3, 4 ], [ 5, 6 ] ]
// 깊은 복사 (간단하게 2차원 배열일 경우 가정)
function deepCopy(arr) {
const res = [];
for (var i = 0; i < arr.length; i++) {
res.push([]);
for (var j = 0; j < arr[i].length; j++) {
res[i].push(arr[i][j]);
}
}
return res;
}
// depth가 더 높아 질 경우를 재귀호출을 이용해 해결
function deepCopy(obj) {
var result = {};
if (Array.isArray(obj)) {
result = obj.slice().map((v) => {
return deepCopy(v);
});
} else if (typeof obj === 'object' && obj !== null) {
for (var attr in obj) {
if (obj.hasOwnProperty(attr)) {
result[attr] = deepCopy(obj[attr]);
}
}
} else {
result = obj;
}
return result;
}
const b = deepCopy(a);
b[0][0] = 9;
console.log(a); // [ [ 1, 2 ], [ 3, 4 ], [ 5, 6 ] ]
console.log(b); // [ [ 9, 2 ], [ 3, 4 ], [ 5, 6 ] ]