"Boldness has genius, power, and magic in it." - Johann Wolfgang von Goethe

JavaScript

[JS] JavaScript 얕은 복사와 깊은 복사

Toproot 2021. 7. 25. 10:08
728x90
728x90

 

 

✏️ 얕은 복사 Shallow Copy

 

const copyUser = Object.assign({}, user) // 복사 : .assign(대상객체, 출처객체)

 

✏️ 깊은 복사 Deep Copy

 

const copyUser = {...user} // 전개 연산자를 사용하여 복사.

 

  • 깊은 복사 : lodash 사용 (.cloneDeep)
 

Lodash Documentation

_(value) source Creates a lodash object which wraps value to enable implicit method chain sequences. Methods that operate on and return arrays, collections, and functions can be chained together. Methods that retrieve a single value or may return a primiti

lodash.com

 

 

Lodash Documentation

_(value) source Creates a lodash object which wraps value to enable implicit method chain sequences. Methods that operate on and return arrays, collections, and functions can be chained together. Methods that retrieve a single value or may return a primiti

lodash.com

 

import _ from 'lodash'

// |1.  {           }      |2.  {           }    | 3.  {           }
// 얕은 복사(Shallow copy), 깊은 복사(Deep copy)

// 객체 데이터 할당
const user = {
  name: 'Heropy',
  age: 85,
  emails: ['thesecon@gmail.com'] // 배열데이터
}

// 깊은 복사 -> lodash 사용.
// 객체 안에 또 다른 참조형 데이터가 있다면 깊은 복사를 권장.
// 참조정보들에 상관없이 복사 가능.
const copyUser = _.cloneDeep(user)
console.log(copyUser === user) // 일치 연산자 true => 같은 메모리 주소

user.age = 22
console.log('user', user) // age: 22
console.log('copyUser', copyUser) // age : 22 => 메모리 주소가 같아 자동 수정됨.

// 의도치 않게 엉뚱한 부분이 수정될 수 도 있음.
// => 따라서 참조형 데이터들(객체, 배열 등)은 복사라는 개념을 사용.

console.log('--------')
console.log('--------')

user.emails.push('neo@zillinks.com') // 가장 뒷부분에 내용 추가
console.log(user.emails === copyUser.emails) // emails 또한 참조형 데이터로 값 변화가 나타남.
console.log('user', user)
console.log('copyUser', copyUser)

 

 

 

728x90
728x90