배열구조분해할당과 객체구조분해할당은 사용방법이 다르다.
let user = {
name: "John",
years: 30,
};
let name = user.name; // 첫번째 방법
let {name} = user; // 두번째 방법
console.log(name);
객체의 프로퍼티값을 새로운 변수에 할당하기위한 방법은 위와 같다.
2가지중 어떤 방법이 좋은가?
2번째 방법이 가독성, 유연성이 좋은것이 확실하다.
let {var1, var2} = {var1:…, var2:…}
let options = {
title: "Menu",
width: 100,
height: 200
};
let {title,width,height} = options;
console.log(title,width,height); // Menu 100 200
배열은 키없이 값만 있기때문에 좌항변수에 값만 할당하면 되는데 객체는 키를 기준으로 값을 가져와야하기 때문에 구조분해할당되는 변수식별자도 객체의 키이름과 같아야 하는 조건이 발생한다.
let {height, width, title} = { title: "Menu", height: 200, width: 100 }
배열구조분해할당은 우항 이터레이터객체의 순서대로 할당이 이루어지는데 객체는 키이름을 기준으로 값을 가져오기때문에 객체프로퍼티의 순서는 중요하지 않다.
키이름이 새로운 변수이름으로 고정되는것은 큰 불편사항이기때문에 엔진은 키이름을 새롭게 부여할수있는 방법을 제공한다.
let {width: w, height: h, title} = {width:23, height:34, title:'box'};
let options = {
title: "Menu"
};
let {width = 100, height = 200, title} = options;
let options = {
title: "Menu"
};
let {width: w = 100, height: h = 200, title} = options;
기본값설정 가능하다.
let options = {
title: "Menu",
height: 200,
width: 100
};
let {title, ...rest} = options;
객체구조분해할당에서도 나머지연산자사용이 가능하다.
객체구조분해할당시 주의할점
let title, width, height;
{title, width, height} = {title: "Menu", width: 200, height: 100};
위 코드에서 {title, width, height}는 객체구조분해할당 표현식이 아닌 코드블럭으로 해석되어 엔진은 변수와 쉼표연산자를 실행한후 할당연산이 수행되어 제대로 결과가 나오지 않는다.
let title, width, height;
({title, width, height} = {title: "Menu", width: 200, height: 100});
객체구조분행할당표현식 전체를 소괄호로 감싸야 엔진이 제대로 해석한다.
중첩객체구조분해할당도 가능하다.
let options = {
size: {
width: 100,
height: 200
}
};
let {
size: {
width,
height
}
} = options;
console.log(width, height);
console.log(size); // 에러발생
중첩구조를 맞추어야 하고 size키는 가져올값이 없다.