Web/JavaScript

[JavaScript] 모던 자바스크립트 Deep Dive 36장 - 디스트럭처링 할당

어징베 2023. 2. 8. 18:49


디스트럭처링 할당(구조 분해 할당)은 구조화된 배열과 같은 이터러블 또는 객체를 비구조화하여 1개 이상의 변수에 개별적으로 할당하는 것을 말한다.


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

const arr = [1, 2, 3];

const [one, two, three] = arr;
console.log(one, two, three); // 1 2 3

const [c, d] = [1];
console.log(c, d); // 1 undefined

const [e, f] = [1, 2, 3];
console.log(e, f); // 1, 2

const [g, ,h] = [1, 2, 3];
console.log(g, h); // 1, 3

배열 디스트럭처링 할당을 위한 변수에 기본값을 설정할 수 있다.

// 기본값
const [a, b, c = 3] = [1, 2];
console.log(a, b, c); // 1 2 3

// 기본값보다 할당된 값이 우선한다.
const [e, f = 10, g = 3] = [1, 2];
console.log(e, f, g); // 1 2 3

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

const user = { firstName: 'Ungmo', lastName: 'Lee'};

// ES6 객체 디스트럭처링 할당
// 변수 lastName, firstName을 선언하고 user 객체를 디스트럭처링하여 할당한다.
// 이때 프로퍼티 키를 기준으로 디스트럭처링 할당이 이루어진다. 순서는 의미가 없다.

// 할당 기준은 프로퍼티 키다.
const { lastName, firstName } = user;

console.log(firstName, lastName); // Ungmo Lee

객체 디스트럭처링 할당은 객체에서 프로퍼티 키로 필요한 프로퍼티 값만 추출하여 변수에 할당하고 싶을 때 유용하다.

const str = 'Hello';
const { length } = str;
console.log(length); // 5

const todo = { id: 1, content: 'HTML', completed: true };
// todo 객체로 부터 id 프로퍼티만 추출한다.
const { id } = todo;
console.log(id); // 1

배열의 요소가 객체인 경우 배열 디스트럭처링 할당과 객체 디스트럭처링 할당을 혼용할 수 있다.

const todos = [
    { id: 1, content: 'HTML', completed: true },
    { id: 2, content: 'CSS', completed: false },
    { id: 3, content: 'JS', completed: false },
];

// todos 배열의 두 번째 요소인 객체로부터 id 프로퍼티만 추출한다.
const [, { id }] = todos;
console.log(id);

중첩 객체의 경우는 다음과 같이 사용한다.

const user = {
    name: 'Lee',
    address: {
        zipCode: '03068',
        city: 'Seoul'
    }
};

// address 프로퍼티 키로 객체를 추출하고 이 객체의 city 프로퍼티 키로 값을 추출한다.
const { address: { city }} = user;
console.log(city); // 'Seoul'