아래는 복사의 개념을 익히기 위한 콘솔창이다.
let profile = {
name: "chulsoo",
age: 8,
school: "daramgeeelementaryschool"
}
undefined
let friendprofile = profile
undefined
friendprofile
{name: 'chulsoo', age: 8, school: 'daramgeeelementaryschool'}
profile.name="yeonghee"
'yeonghee'
profile
{name: 'yeonghee', age: 8, school: 'daramgeeelementaryschool'}
//profile에는 yeonghee로 바뀌어있지만, friendprofile은 그대로 있길 바라는 상황
undefined
friendprofile
{name: 'yeonghee', age: 8, school: 'daramgeeelementaryschool'}
//그러나 friendprofile도 영희로 같이 변했다. 문제가 있다.
문제를 해결하기 위해서는 아래 friendprofile처럼 지정하면 된다.
let profile = {
name: "chulsoo",
age: 8,
school: "daramgeeelementaryschool"
}
undefined
let friendprofile = {
name: profile.name,
age: profile.age,
school: profile.school
}
이걸 빨리 쓰려면
const friendprofile2 = {...profile}
이라고 쓰면 됨.
엄밀히 말하면 이건 복사하는게 아니고 새로 만드는 것으로서
원본 객체와 배열을 유지하기 위해서 이용된다.
그런데 이건 얕은복사라고 해서... 복사가 안들어가는 것도 있다.
이를타면 아래와 같은 것은 like를 빼고 복사가 된다.
let profile = {
name: "chulsoo",
age: 8,
school: "daramgeeelementaryschool"
like:{ one: "candy", two: "chocolate"}
}
이럴 경우 문자열로 새로 만들어서 복사를 하는 방법이 있다.
이를 깊은 복사라고 한다.
이때는
JSON.stringify(profile)
const profile2=JSON.parse(JSON.stringify(profile2))
하면 됨.
그러나 이렇게 하면 속도가 좀 느리기때문에
실무에서는 Lodash를 사용한다.
https://www.npmjs.com/package/lodash에서 다운받으면 됨.