Destructuring (비구조화, 파괴)

구조화된 배열 또는 객체를 Desturcturing하여 개별적인 변수에 할당하는 것.
배열 또는 객체 리터럴에서 필요한 값만을 추출하여 변수에 할당하거나 반환할 때 유용

 

1. 배열 Destructuring 

  • 배열의 각 요소를 추출하여 변수 리스트에 할당
  • 추출/할당 기준은 배열의 인덱스
const arr = [1, 2, 3];

// 배열의 인덱스를 기준으로 배열로부터 요소를 추출하여 변수에 할당
// 변수 one, two, three가 선언되고 arr(initializer(초기화자))가 Destructuring(비구조화, 파괴)되어 할당된다.
const [one, two, three] = arr;
// 디스트럭처링을 사용할 때는 반드시 initializer(초기화자)를 할당해야 한다.
// const [one, two, three]; // SyntaxError: Missing initializer in destructuring declaration

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

 

할당연산자(=) 왼쪽에 배열형태의 변수 리스트가 있고, 오른쪽의 배열은 인덱스를 기준으로 할당된다

let x, y, z;

[x, y] = [1, 2];
console.log(x, y); // 1 2

[x, y] = [1];
console.log(x, y); // 1 undefined

[x, y] = [1, 2, 3];
console.log(x, y); // 1 2

[x, , z] = [1, 2, 3];
console.log(x, z); // 1 3

// 기본값
[x, y, z = 3] = [1, 2];
console.log(x, y, z); // 1 2 3

[x, y = 10, z = 3] = [1, 2];
console.log(x, y, z); // 1 2 3

// spread 문법
[x, ...y] = [1, 2, 3];
console.log(x, y); // 1 [ 2, 3 ]

 

2. 객체 Destructuring 

  • ES6의 객체 destructuring은 각 프로퍼티를 객체로부터 추출하여 변수 리스트에 할당
  • 할당 기준은 프로퍼티 이름(키)
const obj = { firstName: 'Ungmo', lastName: 'Lee' };

// 프로퍼티 키를 기준으로 디스트럭처링 할당이 이루어진다. 순서는 의미가 없다.
// 변수 lastName, firstName가 선언되고 obj(initializer(초기화자))가 Destructuring(비구조화, 파괴)되어 할당된다.
const { lastName, firstName } = obj;

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

 

할당연산자(=) 왼쪽에 객체형태의 변수 리스트가 있고, 프로퍼티 이름으로 값을 추출한다

// 프로퍼티 키가 prop1인 프로퍼티의 값을 변수 p1에 할당
// 프로퍼티 키가 prop2인 프로퍼티의 값을 변수 p2에 할당
const { prop1, prop2 } = { prop1: 'a', prop2: 'b' };
console.log({ prop1, prop2 }); // { prop1: 'a', prop2: 'b' }

// default value
const { prop1, prop2, prop3 = 'c' } = { prop1: 'a', prop2: 'b' };
console.log({ prop1, prop2, prop3 }); // { prop1: 'a', prop2: 'b', prop3: 'c' }

 

객체 비구조화는 프로퍼티 이름으로 필요한 프로퍼티 값만을 추출할 수 있다.

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

// todos 배열의 요소인 객체로부터 completed 프로퍼티만을 추출한다.
const completedTodos = todos.filter(({ completed }) => completed);
console.log(completedTodos); // [ { id: 1, content: 'HTML', completed: true } ]

filter 메소드의 콜백함수는 todos배열을 순회하며 첫번째 인자로 대상배열의 요소를 받는다.

그래서 completed가 true인 객체만 반환한다

이때 필요한 프로퍼티만을 추출할 수 있다.

 

중첩객체의 경우는 아래와 같이 사용한다

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

const { address: { city } } = person;
console.log(city); // 'Seoul'

 

fail-soft 비구조화는 값이 찾아지지 않더라도 오류가 생기지 않고 undefined를 반환하는 것을 의미한다.

// Fail-soft 비구조화 (Fail-soft는 고장이 나도 작동하도록 짠 프로그램을 말한다)
var [a] = [];
a === undefined;

// 기본 값이 있는 Fail-soft 비구조화
var [a = 1] = [];
a === 1;

하지만, 중첩된 객체에서의 프로퍼티는 fail-soft가 적용되지 않는다는 점에 유의해야 합니다.

let options = {},
  // `delay` would be `undefined`, but trying
  // to assign to `name` is an error
  // since `options.info` is already `undefined`
  {
    delay, 
    info: { name },
  } = options

options.info와 delay는 모두 undefined를 반환한다.

하지만, info안의 name은 error을 발생시킨다. ( name을 감싸고 있는 info가 이미 undefined이기 때문에 ) 

 

 

참고, 출처: 

https://www.benmvp.com/blog/learning-es6-destructuring/

https://poiemaweb.com/es6-destructuring

'엘리스 ai 트랙 > FE' 카테고리의 다른 글

HTTP  (0) 2022.03.13
기본값+rest+spread  (0) 2022.03.07
IIFE (즉시 호출 함수 표현식)  (0) 2022.02.28
var vs let vs const  (0) 2022.02.21
스코프  (0) 2022.02.14

+ Recent posts