구조 분해 할당[JavaScript]

배동우·2023년 10월 19일
0

구조 분해 할당(destructuring)?
구조 분해 할당이란 구조화된 배열이나 객체를 개별적인 변수에 할당하는 것을 말한다.
객체나 배열에 저장된 전체가 아닌 일부만 필요할 때 사용하는 문법이다.

배열에서의 구조 분해 할당

저장된 배열에서 구조 분해 할당

let arr = ['apple', 'banana', 'grape'];
let [a, b, c] = arr;
console.log(a); //apple
console.log(b); //banana
console.log(c); //grape

과일 이름이 담긴 배열을 구조 분해 할당을 통해 각각 요소는 a,b,c 변수에 할당된다.

  • 쉼표를 사용해 요소를 건너뛰고 할당할 수 있다.
let arr = ['apple', 'banana', 'grape'];
let [a,,b] = arr;
console.log(a); //apple
console.log(b); //grape

배열 할당과 동시에 구조 분해

let [a, b, c] =  ['apple', 'banana', 'grape'];
console.log(a); //apple
console.log(b); //banana
console.log(c); //grape

위와 같이 미리 선언되어 있는 배열이아닌 배열 할당과 동시에 구조 분해를 할 수 있다.
또한 기본값 설정도 가능하다
요소가 할당되지 않았을때 할당할 기본 값도 설정할 수 있다.

let [a, b='strawberry', c] =  ['apple',, 'grape'];
console.log(a); //apple
console.log(b); //strawberry
console.log(c); //grape

스프레드 연산자 활용
스프레드 연산자를 활용해 남은 요소들을 묶어 새로운 배열을 만들 수 있다.

let { userName, ...C } = user;
let arr = ['apple', 'banana', 'grape'];
let [a, ...b] = arr;
console.log(a); //apple
console.log(b); //['banana','grape']

apple을 담고 있는 a라는 변수와 banana와 grape를 담은 b라는 배열

객체에서의 구조 분해 할당

저장된 객체의 구조 분해 할당
배열과 마찬가지로 저장된 객체를 통해 구조 분해 할당을 진행할 수 있다.

let user = {
  userName: 'dongwoo',
  age: 28,
  skill: 'js',
};

let { userName, age, skill } = user;
console.log(userName); //dongwoo
console.log(age); //28
console.log(skill); //js

주의 해야 할 점은 배열에서는 배열의 인덱스가 키 값이지만
객체에서는 프로퍼티 키를 키값으로 사용하기 때문에 할당하고자 하는 변수의 이름을 프로퍼티 키와 같은 이름을 사용해야 한다는 점이다.
다른 이름으로 사용하고자 할때는 아래와 같은 방법으로 저장이 가능하다

let user = {
  userName: 'dongwoo',
  age: 28,
  skill: 'js',
};

let { userName: NAME, age: AGE, skill: SKILL } = user;
console.log(NAME); //dongwoo
console.log(AGE); //28
console.log(SKILL); //js

객체 할당과 동시에 구조 분해
배열과 마찬가지로 객체를 선언함과 동시에 구조 분해를 진행할 수 있다.

let { userName, age, skill } = {
  userName: 'dongwoo',
  age: 28,
  skill: 'js',
};
console.log(userName); //dongwoo
console.log(age); //28
console.log(skill); //js

또한 프로퍼티가 없는 경우 기본 값을 설정할 수 있다.

let {userName,age,skill = 'java'} = {
  userName: 'dongwoo',
  age: 28,
};
console.log(userName); //dongwoo
console.log(age); //28
console.log(skill); //java

스프레드 연산자 활용
스프레드 연산자를 활용해 나머지 프로퍼티를 묶어 새로운 객체를 만들 수 있다.

let user = {
  userName: 'dongwoo',
  age: 28,
  skill: 'js',
};
let { userName, ...ageSkill } = user;
console.log(userName); //dongwoo
console.log(ageSkill); //{ age: 28, skill: 'js' }

dongwoo를 담고있는 userName과 ageSkill이라는 객체

구조 분해 할당을 사용하면 코드의 길이를 줄이고 배열이나 객체를 쉽게 변수에 저장할 수 있다

profile
강아지를 키우는 프론트엔드 개발자 ٩(๑•̀o•́๑)و

0개의 댓글

관련 채용 정보