[javascript] 구조 분해 할당

개발새발🦶·2023년 2월 2일
0
post-thumbnail

구조 분해 할당

구조 분해 할당(디스트럭처링 할당)은 구조화된 배열과 객체를 구조를 파괴하여 1개 이상의 변수에 개별적으로 할당하는 것을 말한다.

배열과 같은 이터러블 또는 객체 리터럴에서 필요한 값만 추출하여 변수에 할당할 때 유용하다.


배열 디스트럭처링 할당

배열 디스트럭처링 할당은 할당 연산자 왼쪽에 값을 할당받을 변수를 선언해야 한다. 이때 변수를 배열 리터럴 형태로 선언한다. 할당의 기준은 배열의 인덱스이다. 개수는 일치할 필요 없음

const arr = [1, 2, 3];
const [one, two, three] = arr;
console.log(one, two);	// 1 2

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

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

// 기존값보다 할당된 값이 우선함.
const [e, f = 10, g = 3] = [1, 2];
console.log(e, f, g);	// 1 2 3

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

객체 디스트럭처링 할당

객체의 각 프로퍼티를 개체로부터 추출하여 변수에 할당한다. 이때 객체 할당의 대상은 객체여야 하며, 할당 기준은 프로퍼티 키다. 배열과 다르게 순서가 상관없으며, 선언된 변수 이름과 프로퍼티 키가 일치하면 할당된다.

const user = { firstName: 'ori', lastName: 'lee' };
// 할당 기준이 프로퍼티 키이므로 순서는 의미 없음
const { lastName, firstName } = user;
console.log(firstName, lastName);	// ori lee

const { firstName: fn = 'ori', lastName: ln } = { lastName: 'lee' };
console.log(fn, ln);	// ori lee

🙌 유용한 팁

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

// String 래퍼 객체에서 length 프로퍼티 추출
const str = 'Hello';
const { length } = str;
console.log(length);	// 5

// 프로퍼티 값만 추출
const todo = { id: 1, content: 'HTML', completed: false };
const { id } = todo;
console.log(id);		// 1

// 
function printTodo({ content, completed }) {
	console.log(`할일 ${content}${completed ? '완료' : '미완'} 상태임`);
}
printTodo({ id: 1, content: 'HTML', completed: true });	// 할일 HTML은 미완 상태임

배열의 요소가 객체인 경우 배열과 객체 디스트럭처링 할당을 혼용할 수 있다.

const todos = [
  { id: 1, content: 'HTML', compelted: true },
  { id: 2, content: 'CSS', compelted: false },
  { id: 3, content: 'JS', compelted: true },
]
const [, { id }] = todos;
console.log(id);	// 2

// 중첩 객체의 경우는 다음과 같이 사용
const user = {
	name: 'Lee',
  	address: {
    	zipCode: '03068',
      	city: 'Seoul'
    }
};
const { address: { city } } = user;
console.log(zipCode);	// '03068'

// Rest 프로퍼티
const { x, ...rest } = { x: 1, y: 2, z: 3 };
console.log(x, rest);   // 1 { y: 2, z: 3 }
profile
발로하는 코딩 정리기

0개의 댓글