Today's Finding

Shallow vs. Deep Copying Objects

paigekim29 2020. 11. 5. 10:56

Shallow Copying Objects:

  • Will duplicate the top-level properties but nested object is shared between original and the copy
  • Array.prototype.slice()
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    const arr = ['peanut''butter''and''jelly'];
     
    arr.slice(1); // ['butter', 'and', 'jelly']
    arr.slice(01); // ['peanut']
    arr.slice(02); // ['peanut', 'butter']
    arr.slice(22); // []
    arr.slice(220); // ['and', 'jelly']
    arr.slice(30);// []
    arr.slice(3100);// ['jelly']
    arr.slice(51); // []
    cs
  • Object.assgin()
    • Object.assign({}, arr)
  • will affect 'array inside array' if it modifies since it is shallow copying objects
  • Pitfall: ๊ณ„์† ์ˆœํ™˜ ์ฐธ์กฐ

Deep Copying Objects:

  • JSON.parse(JSON.stringify(object))
  • Pitafall: if you put user's method, it will cause an error.
  • ์„œ๋ฒ„ ํ†ต์‹ ์—์„œ๋Š” ๋”ฎ์นดํ”ผ๊ฐ€ ๋งž์Œ
  • ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ๋Š” ๊ฐ์ฒด๋‚˜ ๋ฐฐ์—ด์ด ์•„๋‹ˆ๋ผ ๊ทธ๋ƒฅ ๊ธ€์ž์ž„

 

 

 

reference:

https://scotch.io/bar-talk/copying-objects-in-javascript

https://medium.com/watcha/๊นŠ์€-๋ณต์‚ฌ์™€-์–•์€-๋ณต์‚ฌ์—-๋Œ€ํ•œ-์‹ฌ๋„์žˆ๋Š”-์ด์•ผ๊ธฐ-2f7d797e008a