JAVASCRIPT
JAVASCRIPT ) 디스트럭처링
Hweb
2024. 7. 26. 15:58
자바스크립트에서 **디스트럭처링(destructuring)**은 배열이나 객체의 값을 쉽게 추출하여 변수에 할당할 수 있는 문법입니다. 이 문법을 사용하면 코드가 간결해지고, 데이터를 처리하는 것이 훨씬 직관적이 됩니다.
1. 배열 디스트럭처링
배열의 요소들을 쉽게 변수로 할당할 수 있습니다.
const arr = [1, 2, 3];
// 배열 디스트럭처링
const [a, b, c] = arr;
console.log(a); // 1
console.log(b); // 2
console.log(c); // 3
- 값 무시하기: 배열에서 특정 값만 필요할 때, 쉼표로 무시할 수 있습니다.
const arr = [1, 2, 3, 4];
const [first, , third] = arr;
console.log(first); // 1
console.log(third); // 3
- 나머지 요소 받기: 나머지 요소들은 rest 연산자(...)를 사용하여 받을 수 있습니다.
const arr = [1, 2, 3, 4, 5];
const [first, second, ...rest] = arr;
console.log(first); // 1
console.log(second); // 2
console.log(rest); // [3, 4, 5]
2. 객체 디스트럭처링
객체의 속성 값을 변수에 쉽게 할당할 수 있습니다.
const obj = { name: 'John', age: 30 };
// 객체 디스트럭처링
const { name, age } = obj;
console.log(name); // 'John'
console.log(age); // 30
- 변수 이름 변경: 객체의 속성 이름과 변수 이름을 다르게 지정할 수 있습니다.
const obj = { name: 'John', age: 30 };
const { name: fullName, age: years } = obj;
console.log(fullName); // 'John'
console.log(years); // 30
- 기본값 설정: 객체에 없는 속성에 기본값을 설정할 수 있습니다.
const obj = { name: 'John' }; // 'age' 속성이 없음
const { name, age = 25 } = obj;
console.log(name); // 'John'
console.log(age); // 25 (기본값)
- 중첩된 객체 디스트럭처링: 객체 안의 객체도 디스트럭처링할 수 있습니다.
const user = {
name: 'Alice',
address: {
city: 'Wonderland',
zip: '12345'
}
};
const { name, address: { city, zip } } = user;
console.log(name); // 'Alice'
console.log(city); // 'Wonderland'
console.log(zip); // '12345'
3. 함수의 매개변수 디스트럭처링
디스트럭처링은 함수의 매개변수에도 사용될 수 있습니다. 특히 객체를 인자로 전달하는 경우 유용합니다.
const user = { name: 'Bob', age: 28 };
function greet({ name, age }) {
console.log(`Hello, my name is ${name} and I'm ${age} years old.`);
}
greet(user); // 'Hello, my name is Bob and I'm 28 years old.'
이렇게 하면 함수 내부에서 객체의 속성에 접근할 때 더 간결한 문법으로 사용할 수 있습니다.
4. 디스트럭처링을 활용한 기본값
배열이나 객체의 디스트럭처링에서 기본값을 설정하여 해당 값이 undefined일 경우 기본값을 사용할 수 있습니다.
const [x = 5, y = 7] = [10];
console.log(x); // 10 (배열에 값이 있음)
console.log(y); // 7 (기본값 사용)
5. 복잡한 데이터 구조에서의 활용
디스트럭처링은 복잡한 데이터 구조(배열의 배열, 객체의 배열 등)를 처리할 때도 매우 유용합니다.
const people = [
{ name: 'John', age: 25 },
{ name: 'Jane', age: 22 },
];
const [{ name: firstName }, { age: secondPersonAge }] = people;
console.log(firstName); // 'John'
console.log(secondPersonAge); // 22
예제
const person = {
name: 'Lee',
address: {
zipCode: '03068',
city: {
do: 'Kyonggi',
si: 'Ansan'
}
},
tel: {
info: [
{ home: '0310001111' },
{ mobile: '01011112222' },
{ office: '0200001111' }
]
}
};
// Lee / Ansan / 01011112222
const { name , address: {city: {si}}, tel: {info: [,{mobile}]}} = person;
console.log(name, si, mobile);
반응형