반응형
Destructuring
구조 분해 할당 구문은 배열이나 객체의 속성을 해체하여 그 값을 개별 변수에 담을 수 있게 하는 JavaScript 표현식입니다. [MDN]
객체나 배열에서 필요한 값을 개별 변수에 저장하는 것
객체 디스트럭처링 (Object destructuring)
const settings = {
notifications: {
follow: true
},
color: {
theme: "yello"
},
};
// 프로퍼티 key값을 기준으로 Destructuring되어 할당된다.
const { notifications: { follow }, color} = settings;
console.log(follow, color); // true { theme: 'yello' }
예시
//선언
const [name, setName] = useState("");
const [password, setPassword] = useState("");
// 디스트럭처링 사용 X
const onChange = (e) => {
if (e.target.name === 'name') {
setName(e.target.value)
}
else if (e.target.name === 'password')
setPassword(e.target.value)
}
// 디스트럭처링 사용 O
const onChange = (e) => {
const { target: { name, value } } = e;
if (name === 'name') {
setName(value)
}
else if (name === 'password')
setPassword(value)
}
함수 디스트럭처링 (Function destructuring)
// 함수 인자값을 destructuring 하여 받음
function saveSettings({ notifications, color: { theme } }) {
console.log(notifications); // { follow: true, alert: true }
console.log(theme) //blue
}
saveSettings({
notifications: {
follow: true,
alert: true
},
color: {
theme: "blue"
}
});
객체 Key 이름 변경 (Object Rename Key)
const settings = {
color: {
chosen_color: "dark",
},
};
let chosenColor = "blue";
console.log(chosenColor); // blue
({color: { chosen_color: chosenColor = "light" }} = settings);
console.log(chosenColor); // dark
배열 디스트럭처링 (Array destructuring)
배열의 인덱스(index) 값 기준으로 할당
ex) React - useState 사용
[변수]
const days = ['Mon', 'Tue', 'Wed'];
const [one, two, three, somthing = "someday"] = days;
console.log(one, two, three, somthing); // Mon Tue Wed someday
[함수]
const days = () => ['Mon', 'Tue', 'Wed'];
const [one, two, three, somthing = "someday"] = days();
console.log(one, two, three, somthing); // Mon Tue Wed someday
스와핑 (Swapping)
let mon = "Sat";
let sat = "Mon";
console.log(`${mon} = "Sat", ${sat} = "Mon"`); // Sat = "Sat", Mon = "Mon"
//Swapping
//sat 변수에 mon값 저장 , mon 변수에 sat값 저장
[sat, mon] = [mon, sat];
console.log(`${mon} = "Sat", ${sat} = "Mon"`); // Mon = "Sat", Sat = "Mon"
배열 디스트럭처링 규칙에 따라서, [ sat, mon ] = [ mon, sat ] 변경
스킵핑 (Skipping ≒ Omitting)
const days = ['mon', 'tue', 'wed', 'thu', 'fri'];
//변수 생략 방법 => ,,, 으로 넘긴 뒤 저장 후 사용 가능
const [, , , thu, fri] = days;
console.log(thu, fri) // thu fri
필요한 값을 얻기 위해 ( , , , ) 콤마를 통해 스킵 가능
객체 초기자 (Shorthand)
const a = 'foo';
const b = 42;
const c = {};
const obj1 = { a: a, b: b, c: c }; // key 와 value 값이 동일하면
console.log(object1.b); //42
// key값 === value값 일때 사용 가능
const obj2 = { a, b, c }; // 하나로 표현 가능
console.log(object2.a); //"foo"
참고자료
노마드 코더 Nomad Coders
코딩은 진짜를 만들어보는거야!. 실제 구현되어 있는 서비스를 한땀 한땀 따라 만들면서 코딩을 배우세요!
nomadcoders.co
https://poiemaweb.com/es6-destructuring
Destructuring | PoiemaWeb
디스트럭처링(Destructuring)은 구조화된 객체(배열 또는 객체)를 Destructuring(비구조화, 파괴)하여 개별적인 변수에 할당하는 것이다. 배열 또는 객체 리터럴에서 필요한 값만을 추출하여 변수에 할
poiemaweb.com
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/Object_initializer
객체 초기자 - JavaScript | MDN
객체는 new Object(), Object.create() 또는 리터럴 표기법 (initializer 표기법)을 사용하여 초기화될 수 있습니다. 객체 초기자(object initializer)는 0개 이상인 객체 속성명 및 관련값 쌍 목록이 콤마로 분리
developer.mozilla.org
반응형