2023.04.02
자바스크립트 스터디 11회차
공부 사이트: https://poiemaweb.com/
6. Destructuring
디스트럭처링(Destructuring): 구조화된 배열 또는 객체를 비구조화시켜서 개별 변수에 할당하는 것
→ 필요한 값만을 추출하여 변수에 할당하거나 반환할 때 유용함.
1) 배열 디스트럭처링
// ES5
var arr = [1,2,3];
var one = arr[0];
var two = arr[1];
var three = arr[2];
// ES6
const arr = [1,2,3];
// 배열의 인덱스를 기준으로 배열로부터 요소를 추출하여 변수에 할당
// 변수 one, two, three가 선언됨.
const [one, two, three] = arr;
왼쪽의 변수 리스트와 오른쪽의 배열은 배열의 인덱스를 기준으로 할당된다.
let x, y, z;
[x,y] = [1,2,3];
console.log(x, y); //1 2
[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
[x, ...y] = [1,2,3];
console.log(x, y); //1 [2, 3]
[예제]
/*
[예제] 년도, 월, 일을 추출
*/
const today = new Date();
const formattedDate = today.toISOString().substring(0,10);
console.log(formattedDate);
const [year, month, day] = formattedDate.split('-');
console.log([year, month, day]);
2) 객체 디스트럭처링
// ES5
var person = { first: 'Gildong', last: 'Hong' };
var firstName = person.first;
var lastName = person.last;
console.log(firstName, lastName);
// ES6
const person = { first: 'Gildong', last: 'Hong' };
const { last, first } = person;
console.log(first, last);
객체 디스트럭처링은 프로퍼티 명(프로퍼티 키)를 기준으로 변수 리스트에 할당된다.
프로퍼티 명과 할당할 변수명을 일치시켜주어야 함.
[예제 1]
프로퍼티 명을 통해 변수에 프로퍼티 값 할당
// 프로퍼티 명을 통해 할당
// 변수 p1과 p2에 각각 'a', 'b' 할당
{
const { prop1: p1, prop2: p2 } = { prop1: 'a', prop2: 'b' };
console.log(p1, p2);
}
// 축약형
{
const { prop1, prop2 } = { prop1: 'a', prop2: 'b' };
console.log({ prop1, prop2 });
}
// 기본 값 할당 가능
{
const { prop1, prop2, prop3 = 'c' } = { prop1: 'a', prop2: 'b' };
console.log({ prop1, prop2, prop3 });
}
[예제 2]
프로퍼티 명을 통해 객체에서 필요한 프로퍼티 값만을 추출
const todos = [
{ id:1, content: '과제', completed: false },
{ id:2, content: '운동', completed: true },
{ id:3, content: '데이트', completed: false }
];
// completed 키를 통해 값을 추출하여 true인 것을 추출하여 변수에 저장
// filter: 인수로 전달받은 콜백 함수를 통과하는 요소를 모아 새로운 배열로 반환
const completedTodos = todos.filter(({ completed }) => completed);
console.log(completedTodos);
[예제 3]
중첩 객체의 경우
// person 객체의 프로퍼티 address 또한 객체임 (중첩 객체)
const person = {
name: 'Hong',
address: {
zipCode: '12345',
city: 'Seoul'
}
};
const { address: { city } } = person;
console.log(city);
'프로그래밍 > js' 카테고리의 다른 글
ES6 lessons 8. 모듈 (0) | 2023.04.03 |
---|---|
ES6 lessons 7. 클래스 (0) | 2023.03.28 |
ES6 lessons 5. 향상된 객체 리터럴 (0) | 2023.03.26 |
ES6 lesson 4. 확장 파라미터 핸들링 (0) | 2023.03.26 |
ES6 lessons 3. 화살표 함수 (0) | 2023.03.26 |