이수연의 티스토리
[5]React ES6 Destructuring 본문
Destructuring
구조 분해를 설명하기 위해 샌드위치 만드는 방법으로 비유를 해보도록 하겠다. 샌드위치를 만들기 위해 냉장고에 모든 것을 꺼내지 않는다. 샌드위치에 들어가는 재료만 꺼내면 된다.
구조 분해도 똑같다. 우리가 작업하는 배열이나 객체가 있을 수 있지만, 이것들에 포함된 일부 항목만 필요할 때도 있다. 구조 분해를 통하면 필요한 것만 쉽게 추출할 수 있어 간편하다.
Destructing Arrays
const vehicles = ['mustang', 'f-150', 'expedition'];
const car = vehicles[0];
const truck = vehicles[1];
const suv = vehicles[2];
배열을 구조 분해할 때 변수를 선언하는 순서가 중요하다.
const vehicles = ['mustang', 'f-150', 'expedition'];
const [car, truck, suv] = vehicles;
자동차와 SUV만 원하는 경우 트럭은 제외하고 쉼표만 남겨두면 된다.
const vehicles = ['mustang', 'f-150', 'expedition'];
const [car, , suv] = vehicles;
함수가 배열을 반환하는 경우 구조 분해가 유용하다.
function claculate(a, b) {
const add = a + b;
const subtract = a - b;
const multiply = a * b;
const divide = a / b;
return [add, subtract, multiply, divide];
}
const [add, subtract, multiply, divide] = calculate(4, 7);
Destructuring Objects
함수 내부에서 객체를 사용하는 기존 방식은 다음과 같다.
const vehicleOne = {
brand: 'Ford',
model: 'Mustang',
type: 'car',
year: 2021,
color: 'red'
}
myVehicle(vehicleOne);
// old way
function myVehicle(vehicle) {
const message = 'My ' + vehicle.type + ' is a ' + vehicle.color + ' ' + vehicle.brand + ' ' + vehicle.model + '.';
}
함수 내부에서 객체를 사용하는 새로운 방법은 다음과 같다.
const vehicleOne = {
brand: 'Ford',
model: 'Mustang',
type: 'car',
year: 2021,
color: 'red'
}
myVehicle(vehicleOne);
function myVehicle({type, color, brand, model}) {
const message = 'My ' + type + ' is a ' + color + ' ' + brand + ' ' + model + '.';
}
객체 속성은 특정 순서로 선언할 필요가 없다는 점에 주의
중첩된 객체를 참조한 다음 콜론과 중괄호를 사용하여 중첩된 객체에서 필요한 항목을 다시 구조 분해하여 깊이 중첩된 객체의 구조를 분해할 수도 있다.
const vehicleOne = {
brand: 'Ford',
model: 'Mustang',
type: 'car',
year: 2021,
color: 'red',
registration: {
city: 'Houston',
state: 'Texas',
country: 'USA'
}
}
myVehicle(vehicleOne)
function myVehicle({ model, registration: { state } }) {
const message = 'My ' + model + ' is registered in ' + state + '.';
}
'react' 카테고리의 다른 글
[7] React ES6 Modules (0) | 2025.03.28 |
---|---|
[6] React ES6 Spread Operator (0) | 2025.03.28 |
[4] React ES6 Array Methods (0) | 2025.03.28 |
[3]ES6 Variables (0) | 2025.03.28 |
[2]React ES6 Classes (0) | 2025.03.17 |