구조 분해 할당

lbr·2022년 7월 11일
0

구조 분해 할당

구조 분해 할당(Destructuring assignment) 다른말로 비구조화 할당 이라고도 부릅니다.

const user = {
  name: 'Heropy',
  age: 85,
  email: 'thesecon@gmail.com'
}

const { name, age, email, address } = user;

console.log(`사용자의 이름은 ${name}입니다.`);
// 사용자의 이름은 Heropy입니다.
console.log(`${name}의 나이는 ${age}세입니다.`);
// Heropy의 나이는 85세입니다.
console.log(`${name}의 이메일 주소는 ${email}입니다.`);
// Heropy의 이메일 주소는 thesecon@gmail.com입니다.
console.log(address);
// undefined

기본값 초기화가 가능합니다.

const { name, age, email, address = 'Korea'} = user;
console.log(address); // Korea
  • address라는 값이 없다면 기본값을 지정할 수 있습니다.
  • undefinded 대신 기본값으로 지정한 Korea가 출력됐습니다.

값이 있다면 기본값이 아닌 실제 값을 출력합니다.

const user = {
  name: 'Heropy',
  age: 85,
  email: 'thesecon@gmail.com',
  address: 'USA'
}

const { name, age, email, address = 'Korea'} = user;
console.log(address); // USA
  • 기본값 Korea가 무시되고 USA가 출력됩니다.

꺼내오는 속성이름이 마음에 들지 않으면 다른이름으로 바꿀 수 있습니다.

const user = {
  name: 'Heropy',
  age: 85,
  email: 'thesecon@gmail.com',
  address: 'USA'
}

const { name: heropy, age, email, address = 'Korea'} = user;

console.log(heropy); // 'Heropy'
  • name: heropy라고 명시하여 꺼내오는 속성은 name으로, 사용하고 싶은 변수 이름은 heropy로 지정할 수 있습니다.

객체 뿐만 아니라 배열도 구조 분해 할당 문법을 사용할 수 있습니다.

const fruits = ['Apple', 'Banana', 'Cherry'];
const [a, b, c, d] = fruits;
console.log(a, b, c, d);
// Apple Banana Cherry undefined
  • 구조분해하려는 데이터 타입에 맞게 기호를 사용해야 합니다.
    앞서 객체를 구조분해했을때는 {}였지만, 지금은 배열을 구조분해 하기 때문에 []로 명시합니다.
  • 배열은 객체 구조 분해와 달리 배열 순서대로 인덱싱 되어서 들어갑니다. 그래서 a, b, c, d에 순서대로 'Apple', 'Banana', 'Cherry', undefinded 가 들어갔습니다.

추출하고 싶지 않은 item은 쉼표만 남겨두어, 순서는 표현하고 변수는 표현하지 않습니다.

예) Apple은 추출하지 않고 Banana만 추출하고 싶을 경우,

const fruits = ['Apple', 'Banana', 'Cherry'];
const [, b] = fruits;
console.log(b);
// Banana

예2) Cherry만 출력하고 싶은 경우,

const fruits = ['Apple', 'Banana', 'Cherry'];
const [, , a] = fruits;
console.log(a);
// Cherry

0개의 댓글