깊은 복사

하태현·2021년 3월 2일
0

javascript

목록 보기
20/23
post-thumbnail

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 ] ]
profile
왜?를 생각하며 개발하기, 다양한 프로젝트를 경험하는 것 또한 중요하지만 내가 사용하는 기술이 어떤 배경과 이유에서 만들어진 건지, 코드를 작성할 때에도 이게 최선의 방법인지를 끊임없이 질문하고 고민하자. 이 과정은 앞으로 개발자로 커리어를 쌓아 나갈 때 중요한 발판이 될 것이다.

0개의 댓글