Javascript

[JS] 구조 분해 할당(Destructuring assignment)

gamzaggang7 2024. 6. 14. 20:38
728x90

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

* 이터러블: 반복 가능한 객체. 배열, 문자열, Map, Set 등

 

배열 구조 분해 할당

var arr = [1, 2, 3]

var one = arr[0]
var two = arr[1]
var three = arr[2]

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

 

ES6의 배열 구조 분해 할당은 배열의 각 요소를 배열로부터 추출해 1개 이상의 변수에 할당한다. 할당의 대상(우변)은 이터러블이어야 하며, 할당 기준은 배열의 인덱스다.

 

const arr = [1, 2, 3]

const [one, two, three] = arr

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

 

할당 연산자 왼쪽에 값을 할당받은 변수를 선언해야 하며 변수를 배열 리터럴 형태로 선언한다. 배열 순서대로 할당된다.

const [one, two, three] = [1, 2, 3]

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

 

변수의 개수와 이터러블의 요소 개수가 일치하지 않아도 된다.

const [a, b] = [1]
console.log(a, b);

const [c, d] = [1, 2, 3]
console.log(c, d);
1 undefined
1 2
const [a, , b] = [1, 2, 3]
console.log(a, b);
1 3

 

변수에 기본값을 설정할 수 있고 기본값보다 할당된 값이 우선한다.

const [a, b, c = 3] = [1, 2];

console.log(a, b, c);
1 2 3
const [a, b = 10, c = 20] = [1, 2];

console.log(a, b, c);
1 2 20

 

 

객체 구조 분해 할당

ES6의 객체 구조 분해 할당은 객체의 각 프로퍼티를 객체로부터 추출하여 1개 이상의 변수에 할당한다. 할당의 대상(우변)은 객체이어야 하며 할당 기준은 프로퍼티 키다. 즉 순서는 의미 없으며 선언된 변수 이름과 프로퍼티 키가 일치하면 할당된다.

var user = { firstname: 'Minsu', lastname: 'Kim' }

const { lastname, firstname } = user;

console.log(firstname, lastname);
Minsu Kim 
const { lastname, firstname } = { firstname: 'Minsu', lastname: 'Kim' }

console.log(firstname, lastname);
Minsu Kim

 

객체의 프로퍼티 키와 다른 변수 이름으로 프로퍼티 값을 할당받으려면 다음과 같이 선언해야 한다.

var user = { firstname: 'Minsu', lastname: 'Kim' }

const { lastname: ln, firstname: fn } = user;

console.log(fn, ln);
Minsu Kim

 

변수에 기본값을 설정할 수 있고 기본값보다 할당된 값이 우선한다.

var user = { firstname: 'Minsu', lastname: 'Kim' }

const { firstname: fn = 'Hyesu', lastname: ln } = user;

console.log(fn, ln);
Minsu Kim
var user = { lastname: 'Kim' }

const { firstname: fn = 'Hyesu', lastname: ln } = user;

console.log(fn, ln);
Hyesu Kim

 

객체에서 프로퍼티 키로 필요한 프로퍼티 값만 추출하여 변수에 할당할 때 유용하다.

const str = 'hello'
const { length } = str
console.log(length);
5
const todo = { id: 1, content: 'HTML', completed: true }
const { id } = todo
console.log(id);
1

 

객체를 인수로 전달받는 함수의 매개변수에도 사용할 수 있다.

function printTodo(todo) {
  console.log(`할 일 ${todo.content}${todo.completed ? '완료' : '비완료'} 상태입니다.`);
}

printTodo({ id: 1, content: 'HTML', completed: true })
할 일 HTML은 완료 상태입니다.

 

위에서 객체를 인수로 전달받는 매개변수 todo에 객체 구조 분해 할당을 사용하면 더 간단하고 가독성 좋게 표현할 수 있다.

function printTodo({content, completed}) {
  console.log(`할 일 ${content}${completed ? '완료' : '비완료'} 상태입니다.`);
}

printTodo({ id: 1, content: 'HTML', completed: true })
할 일 HTML은 완료 상태입니다.

 

배열 요소가 객체인 경우 배열 할당과 객체 할당을 혼용할 수 있다.

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

const [, { id }] = todos
console.log(id);
2

 

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

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

const { address: { city } } = user
console.log(city);
Seoul

address 프로퍼티 키로 객체를 추출하고 이 객체의 city 프로퍼티 키로 값을 추출한다.

 

객체 할당 변수에 rest 파라미터나 rest 프로퍼티를 사용할 수 있다.

const { x, ...rest } = { x: 1, y: 2, c: 3 }

console.log(x, rest);
1 { y: 2, c: 3 }
728x90

'Javascript' 카테고리의 다른 글

npm 프로젝트 기본 구성  (1) 2024.05.22