디스트럭처링 할당 const { profile : { address }} = user;

HG·2023년 3월 17일
0
const user = {
    name: "ohhk",
    profile: {
        phoneNumber: "010-1234-5678",
        address: "Seoul",
    },
};

const {
    profile: { address },
} = user;

console.log(address);
	

의 콘솔값이 무엇인지 알겠다면, 그냥 넘어가시는걸 추천한다.

디스트럭처링 할당은 ES6에서 도입된 문법이다.

나는 이걸 코딩테스트때 처음 접했는데, 그때 접한 이유는 스프레드 문법 때문이었다.

실무에서는 객체할당 때문에 가끔 쓰고는 하는데, 사실 자주 햇갈리는 경우가 참 많다.

그래서 정리하고자 이 글을 쓴다.

1) 배열 디스트럭처링 할당

배열 디스트럭처링 할당은 다들 많이 써봤거나, 쉽게 이해하는 경우가 많다.

const a = [1,2,3,4,5]
const [b,c,d] = a 

에서 b,c,d는 index순서대로 값이 들어간다. 이건 간단하다.

조금 햇갈린다면, Rest를 사용할때가 될거다.

보통 이거를 리액트에서 component 옵션같은걸 받을때 많이 쓰는데,

배열에서 한번 살펴보자.

const a = [1,2,3,4,5]
const [b,c,...d] = a 

라고 한다면, d = [3,4,5]가된다.

주의해야할 점이 있다면, Rest 요소는 마지막에 위치해야한다는 것이다.

2) 객체 디스트럭처링 할당

객체 디스트럭처링 할당도 사실 크게 문제될건 없다! 프로퍼티값을 빼고 분해하고 넣고 하기 전까진..

기본적으로 디스트럭처링 자체가 부숴서 할당하는것이기 때문에 (부순다고해서 기존객체에 영향은 없다)

const user = {
    name: "ohhk",
    profile: {
        phoneNumber: "010-1234-5678",
        address: "Seoul",
    },
};

const {
    name
} = user;

console.log(name);
	

을하면, user 객체를 부숴서 name이라는 키만 빼서 할당하는 것이다.

근데 좀 더 나아가서

const user = {
    name: "ohhk",
    profile: {
        phoneNumber: "010-1234-5678",
        address: "Seoul",
    },
};

const {
    name : userName
} = user;

console.log( userName);
	

을 하면, user를 부숴서 name을 가져오고, userName에 할당까지 이루어진다.

하지만 객체를 할당하는 경우엔 깊은복사가 이루어진다.

const user = {
    name: "ohhk",
    profile: {
        phoneNumber: "010-1234-5678",
        address: "Seoul",
    },
};

const {
    profile : ohhkProfile
} = user;


ohhkProfile.address = 'Canada'

console.log(user)

를 해보면 결과는 user의 profile 의 address, ohhkProfile의 address가 변경된다.

객체 할당시에는 깊은복사가 이루어지고 있기 때문이다.

const user = {
    name: "ohhk",
    profile: {
        phoneNumber: "010-1234-5678",
        address: "Seoul",
    },
};

const {
    profile: { address },
} = user;

console.log(address);
	

이제 첫 질문지를 받아보면, {}가 없다면 user.profile을 할당받는데, {}가 있기 때문에 user.profile.address를 할당 받는다.

만약 {address}가 아닌 {...address}를 받는다면, 어떻게 될까?

그냥 profile이 될것이다.

profile
Making Body, Making Food, Making Co?de

0개의 댓글