JavaScript

얕은 복사 & 깊은 복사

kelly09 2024. 6. 16. 00:47

🍰 얕은 복사 (Shallow Copy)

: 객체의 1단계 속성들만 복사

  • 객체의 속성 중 하나가 다른 객체를 참조 -> 원본 객체와 복사된 객체가 공유
  • 중첩된 객체배열은 복사 X, 참조만 복사
const original = {
  name: 'Alice',
  age: 25,
  address: {
    city: 'Wonderland',
    zip: '12345'
  }
};

// 얕은 복사
const shallowCopy = { ...original };

console.log(shallowCopy);
// { name: 'Alice', age: 25, address: { city: 'Wonderland', zip: '12345' } }

shallowCopy.name = 'Bob';
shallowCopy.address.city = 'Atlantis';

console.log(original.name); // 'Alice'
console.log(original.address.city); // 'Atlantis'

🍰 깊은 복사 (Deep Copy)

: 객체의 모든 중첩된 객체배열까지 재귀적으로 복사

  • 완전히 새로운 객체를 만듦
  • 원본 객체와 완전히 독립적
  • 한 쪽에서 데이터를 변경해도 다른 쪽에 영향을 미치지 않음

객체의 깊은 복사를 수행하는 재귀적인 방법

function cloneDeep(object) {
  return Object.fromEntries(
    // fromEntries: 객체의 속성을 [key, value]쌍의 배열로 반환
    Object.entries(object).map(([key, value]) => {
      // 배열의 각 [key, value] 쌍에 대해 콜백 함수 적용
      // [key, value] 쌍을 받아서 깊은 복사 수행, [key, newValue] 반환
      let type = typeof value; // 현재 값의 타입 확인
      // typeof는 원시 타입과 객체인지 여부 확인 가능
      if (value && type === 'object') {
        // 값이 null이 아닌 객체인 경우에 참이 됨
        // null도 object로 판별돼서 추가적으로 value의 존재 여부 체크
        value = cloneDeep(value); // 배열이나 객체인 경우 재귀적으로 cloneDeep 함수 호출
        // 중첩된 모든 객체와 배열 깊은 복사함
      }
      return [key, value]; // value가 기본형이면 그대로 반환, 객체면 깊은 복사된 객체 반환
    })
  );
}