오브젝트는 참조복사를 한다.

오브젝트의 복사에 대해서 알고 있는 Object.assign은 shallow copy를 한다.

1계층 까지의 복사를 하게된다. 아래의 예로 차이점을 확인할 수 있다.

shallow copy

const output = (obj: {}) => {
  console.log(JSON.stringify(obj, null, 2));
};

const change1 = (obj: any) => {
  obj['x'] = 'change';
};

const change2 = (obj: any) => {
  obj['x']['xx'] = 'change';
};

const objectA = {
  x: {
    xx: 1,
    yy: 2,
  },
};

output(objectA);
// {
//   "x": {
//     "xx": 1,
//     "yy": 2
//   }
// }

change1(Object.assign({}, objectA));
output(objectA);
// {
//   "x": {
//     "xx": 1,
//     "yy": 2
//   }
// }

change2(Object.assign({}, objectA));
output(objectA);
// {
//   "x": {
//     "xx": "change",
//     "yy": 2
//   }
// }

deep copy

import * as lodash from 'lodash';

const output = (obj: {}) => {
  console.log(JSON.stringify(obj, null, 2));
};

const change1 = (obj: any) => {
  obj['x'] = 'change';
};

const change2 = (obj: any) => {
  obj['x']['xx'] = 'change';
};

const objectA = {
  x: {
    xx: 1,
    yy: 2,
  },
};

output(objectA);
// {
//   "x": {
//     "xx": 1,
//     "yy": 2
//   }
// }

change1(lodash.cloneDeep(objectA));
output(objectA);
// {
//   "x": {
//     "xx": 1,
//     "yy": 2
//   }
// }

change2(lodash.cloneDeep(objectA));
output(objectA);
// {
//   "x": {
//     "xx": 1,
//     "yy": 2
//   }
// }

'Javascript' 카테고리의 다른 글

JSON.stringify  (0) 2022.06.19
Object.assign 의 사용법  (0) 2022.06.19
배열 조작  (0) 2022.06.19

+ Recent posts