해당 포스팅은 위키북스의 모던 자바스크립트 Deep Dive라는 책을 독학하며 기록하는 글입니다.

디스트럭처링 할당 (구조분해)

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

배열

배열에 들어있는 값들을 변수에 할당하는 방식은 다음과 같다.

const arr = [1, 2, 3];

const [one, two, three] = arr;

console.log(one); // 1
console.log(two); // 2
console.log(three); // 3

할당시키고 싶은 변수를 대괄호([])로 묶은 것을 변수 선언 키워드(const, let, var)와 함께 좌변에 위치시키고, 할당할 값들을 담은 배열을 우변에 위치시키면 배열의 요소들이 순서대로 좌변의 변수들에 할당된다.

이때 할당의 기준은 인덱스로 요소들이 순서대로 할당되는 것으로 할당하고 싶지 않은 요소가 있을 때는 변수들 사이에 ,로 순서를 명시해줘야 한다.

const arr = [1, 2, 3];

const [one, , three] = arr;

console.log(one); // 1
console.log(two); // Error: two is not defined
console.log(three); // 3

또한 변수에 기본값을 설정해 줄 수 있으나 할당되는 값이 우선순위가 높다는 것을 기억해야 한다.

const arr = [1, 2];

const [one, two, three = 3] = arr;

console.log(one); // 1
console.log(two); // 2
console.log(three); // 3

Rest 파라미터 또한 구조분해에서 사용할 수 있다.

const arr = [1, 2, 3];

const [one, ...other] = arr;

console.log(one); // 1
console.log(other); // [2, 3]

객체

객체를 구조분해하기 위해서는 변수명을 객체에서 사용하고 있는 프로퍼티키로 사용해야 한다. 즉 할당의 기준이 배열과 같이 인덱스가 아니라 프로퍼티 키라는 말이다.
또한 배열과 다르게 할당하고자 하는 변수들을 중괄호({})로 묶어줘야 한다.

const name = {
  firstName: 'jaehyeok',
  lastName: 'Han'
}

const {lastName, firstName} = name;

console.log(firstName); // jaehyeok
console.log(lastName); // Han

배열과 마찬가지로 기본값을 설정할 수 있다.

const name = {
  lastName: 'Han'
}

const {lastName, firstName = 'Kim'} = name;

console.log(firstName); // jaehyeok
console.log(lastName); // Kim

또한 다른 변수 이름으로 할당받을 수도 있다.

const name = {
  firstName: 'jaehyeok',
  lastName: 'Han'
}

const {lastName: two, firstName: one} = name;

console.log(one); // jaehyeok
console.log(two); // Han

혼용

객체가 배열안에 담겨져 있을 때 원하는 값만 추출하길 원한다면 다음과 같이 응용해서 사용할 수도 있다.

const member = [
  {name: 'Han', age: 7, gender: 'male'},
  {name: 'seo', age: 9, gender: 'male'},
  {name: 'Jung', age: 8, gender: 'male'}
];

// member의 두번째 요소 객체의 name프로퍼티의 값을 name변수에 할당
const [, {name}] = member;
console.log(name); // seo
profile
I Will be Relaxed Person

0개의 댓글