uxtry

es6: Array and object destructing(배열 및 객체 비구조화) 본문

ES6 주요 문법 (es6:)

es6: Array and object destructing(배열 및 객체 비구조화)

uxtry 2024. 10. 29. 17:31

배열, 객체, 비구조화 with chatGPT

 

배열 및 객체 비구조화(Destructuring)는 배열이나 객체에서 값을 추출하여 개별 변수에 쉽게 할당하는 ES6 문법입니다. 이를 통해 코드가 간결해지고 가독성이 좋아집니다.

 

1. 배열 비구조화  (Array Destructuring)

배열 비구조화는 배열의 요소를 쉽게 변수에 할당하는 방법입니다. 배열의 각 위치에 있는 값을 변수에 할당할 수 있습니다.

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

console.log(a); // 1
console.log(b); // 2
console.log(c); // 3

 

일부 요소만 할당

필요한 위치에 있는 요소만 추출할 수 있습니다.

const numbers = [1, 2, 3, 4];
const [first, , third] = numbers;

console.log(first); // 1
console.log(third); // 3

 

기본값 설정

배열에 값이 없으면 기본값을 지정할 수 있습니다.

const numbers = [1];
const [a, b = 10] = numbers;

console.log(a); // 1
console.log(b); // 10 (기본값)

 

나머지 요소 추출

나머지 요소들은 ... 연산자를 사용해 하나의 배열로 받을 수 있습니다.

const numbers = [1, 2, 3, 4, 5];
const [first, ...rest] = numbers;

console.log(first); // 1
console.log(rest);  // [2, 3, 4, 5]

 

2. 객체 비구조화 (Object Destructuring)

객체 비구조화는 객체의 프로퍼티를 변수로 쉽게 추출할 수 있는 방법입니다.

const person = { name: "Alice", age: 25 };
const { name, age } = person;

console.log(name); // "Alice"
console.log(age);  // 25

 

다른 변수 이름으로 할당

객체 프로퍼티를 다른 이름의 변수로 할당할 수 있습니다.

const person = { name: "Alice", age: 25 };
const { name: personName, age: personAge } = person;

console.log(personName); // "Alice"
console.log(personAge);  // 25

 

기본값 설정

객체에 해당 프로퍼티가 없을 때 기본값을 지정할 수 있습니다.

const person = { name: "Alice" };
const { name, age = 30 } = person;

console.log(name); // "Alice"
console.log(age);  // 30 (기본값)

 

중첩 객체 비구조화

객체가 중첩된 경우, 중첩된 프로퍼티도 비구조화 할 수 있습니다.

const person = {
  name: "Alice",
  address: {
    city: "Wonderland",
    zip: 12345,
  }
};

const { name, address: { city, zip } } = person;

console.log(city); // "Wonderland"
console.log(zip);  // 12345

 

3. 함수 매개변수에서 비구조화 사용

함수의 매개변수에서도 비구조화를 사용할 수 있어, 특정 속성만 추출하여 사용할 수 있습니다.

function greet({ name, age }) {
  console.log(`Hello, ${name}. You are ${age} years old.`);
}

const person = { name: "Alice", age: 25 };
greet(person); // "Hello, Alice. You are 25 years old."

 

요약

  • 배열 비구조화: 배열 요소를 개별 변수로 추출하며 기본값, 나머지 요소 등 옵션이 가능.
  • 객체 비구조화: 객체 속성을 변수로 추출하며 기본값, 다른 이름, 중첩 객체 등 옵션이 가능.
  • 함수 매개변수 비구조화: 함수 매개변수에 비구조화 적용 가능.

비구조화를 통해 데이터를 더 쉽게 다룰 수 있으며, 특히 많은 속성을 가지는 데이터에서 유용합니다.