디스트럭처링(구조 분해 할당)
구조화된 배열 또는 객체를 파괴하여 1개 이상의 변수에 개별적으로 할당하는 것. 객체 또는 배열에서 필요한 값만을 추출하여 변수에 할당할 때 유용.
왜 디스트럭처링이 필요한가?
객체에서 값을 찾거나 복제하고 싶을 때 ES5에서는 중복이 발생한다.
1 2 3 4 5 6 7
| var expense = { type: 'Business', amount: '$45 USD', };
var type = expense.type; var amount = expense.amount;
|
같은 방식으로 값을 찾거나 복제할 때 ES6는 코드 중복을 줄일 수 있다.
1 2 3 4 5 6
| const { type } = expense; const { amount } = expense;
const { type, amount } = expense; console.log(type, amount);
|
객체에서 디스트럭처링 할당
아래 예제에서 파라미터로 받아온 file로 내부의 값을 조회하여 return할 때 매번 file.이라고 입력해야 하는데,디스트럭처링 할당을 하면 그럴 필요가 없다.
객체 디스트럭처링 할당 방법
- 객체의 각 프로퍼티를 추출하여 1개 이상의 변수에 할당하는데 여러 개의 변수를 객체 리터럴{} 형태로 선언한다. 할당 기준은 프로퍼티 키이다. 이때 주의할 점은 반드시 변수명은 프로퍼티 키의 이름과 동일해야 한다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| var savedFiled = { extension: 'jpg', name: 'repost', size: 14040, };
function es5FileSummary(file) { return `The fils ${file.name}.${file.extension} is of size ${file.size}`; }
console.log(es5FileSummary(savedFiled));
function es6FileSummary({ name, extension, size }, { color }) { return `${color} The fils ${name}.${extension} is of size ${size}`; }
console.log(es6FileSummary(savedFiled, { color: 'red' }));
|
중첩된 객체의 디스트럭처링 할당
1 2 3 4 5 6 7 8 9 10 11 12
| const person = { name: 'Lee', address: { zipCode: '03068', city: 'Seoul', }, };
const { address: { city }, } = person; console.log(city);
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| var metadata = { title: 'Scratchpad', translations: [ { locale: 'de', localization_tags: [], last_edit: '2014-04-14T08:43:37', url: '/de/docs/Tools/Scratchpad', title: 'JavaScript-Umgebung', }, ], url: '/en-US/docs/Tools/Scratchpad', };
var { title: englishTitle, translations: [{ title: localeTitle }], } = metadata;
console.log(englishTitle); console.log(localeTitle);
|
배열의 디스트럭처링 할당
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| var arr = [1, 2, 3];
var one = arr[0]; var two = arr[1]; var three = arr[2];
console.log(one, two, three);
const arr = [1, 2, 3];
const [one, two, three] = arr;
console.log(one, two, three);
|
- 프로퍼티를 디스트럭처링하고 싶을 때는 {}, 기준: 프로퍼티 키
- Element를 디스트럭처링하고 싶을 때는 [], 기준: 인덱스
Reference
poiemaweb
ES6 Javascript:The Complete Developer’s Guide
Destructuring assignment