코딩 공부/React

[React] ES6객체와 배열 구조 분해를 사용한 대입 - 가온 코딩

Cosmic-dust 2022. 7. 22. 18:06
728x90
반응형

리액트에서는 ES2016부터 객체와 배열을 다루는 방법과, 객체와 배열 안에서 변수의 영역을 제한하는 방법을 다양하게 제공하기 시작했다.

 

이런 기능으로는 구조 분해(destructuring), 객체 리터럴 개선, 스프레드 연산자(spread operator) 등이 있다.

 

1. 구조 분해

구조 분해를 사용하면 객체 안에 있는 필드 값을 원하는 변수에 대입할 수 있다.

아래 sandwich 객체에는 4개의 필드가 있는데 그 중에서 bread와 meat의 필드값만 필요한 상황이다.

// Destructuring Assignment

var sandwich =  {
      bread: "dutch crunch",
      meat: "tuna",
      cheese: "swiss",
      toppings: ["lettuce", "tomato", "mustard"]
}

var {bread, meat} = sandwich

//let bread = sandwich.bread;
//let meat = sandwich.meat;

console.log(bread, meat)

bread = "garlic"
meat = "turkey"

console.log(bread,meat)
console.log(sandwich.bread, sandwich.meat)

한글 예시

const sandwich = {
    bread: "더치 크런치",
    meat: "참치",
    cheese: "스위스",
    toppings: ["상추", "토마토", "머스타드"]
};

// const { bread, meat} = sandwich;

let { bread, meat} = sandwich;

bread = "마늘";
meat = "칠면조";

console.log(bread); // 마늘
console.log(meat);  // 칠면조

console.log(sandwich.bread, sandwich.meat); // 더치 크런치 참치

sandwich.bread = "안녕"
sandwich.meat = "하하"

console.log(bread); // 마늘
console.log(meat);  // 칠면조

console.log(sandwich.bread, sandwich.meat); // 안녕 하하

 

2. 객체를 분해해서 함수의 인자로 넘기기

 

 

// Function with object arguments

var lordify = regularPerson => {
  console.log(`${regularPerson.firstname} of Canterbury`)
}

var regularPerson = {
  firstname: "Bill",
  lastname: "Wilson"
}

lordify(regularPerson)

한글 예시

 const lordify = regularPerson => {
     console.log(`캔터베리의 ${regularPerson.firstname}`);
 };

 var regularPerson = {
     firstname: "가온",
     lastname: "얍"
 };

 lordify(regularPerson); //캔터베리의 가온

 

 

 

3.객체의 구조 분해 형태를 함수의 인자로 사용하기

 

객체의 필드에 접근하기 위해 점(.)과 필드 이름을 사용하는 대신, regularPerson에서 필요한 값을 구조 분해로 가져올 수도 있다.

// Destructuring object arguments

var lordify = ({firstname}) => 
  console.log(`${firstname} of canterbury`)

var regularPerson = {
  firstname: "Dale",
  lastname: "Smith"
}

lordify(regularPerson)
const lordify = ({firstname}) => {
    console.log(`캔터베리의 ${firstname}`)
};

const regularPerson = {
    firstname: "가온",
    lastname: "얍"
};

lordify(regularPerson); //캔터베리의 가온

 

// Destructuring object arguments

var lordify = ({firstname}) => 
  console.log(`${firstname} of canterbury`)

var regularPerson = {
  firstname: "Dale",
  lastname: "Smith",
  spouse: {
    firstname: "계영",
    lastname: "이"
  }
}

lordify(regularPerson)
const lordify = ({spouse: {firstname} }) => {
    console.log(`캔터베리의 ${firstname}`);
};

const regularPerson = {
    firstname: "가온",
    lastname: "얍",
    spouse: {
        firstname: "아녕",
        lastname: "욥"
    }
};

lordify(regularPerson); //캔터베리의 아녕

 

4. 배열 구조 분해

배열을 구조 분해해서 값을 뽑아낼 수도 있다.

배열의 세 번째 원소를 변수에 대입하고 싶다고 가정하면 아래와 같이 된다.

불필요한 값을 콤마(,)를 사용해 생략하는 리스트 매칭(list matching)을 사용할 수도 있다.

변수에 대입하지 않고 무시하고 싶은 원소의 위치에 아무 것도 넣지 않으면 리스트 매칭을 사용하는 것이다.

앞에서 본 것과 같은 배열에서 최초의 두 원소를 콤마로 대치하면 아래와 같다.

// Destructuring Arrays

var [firstResort] = ["Kirkwood", "Squaw", "Alpine"]

console.log(firstResort)

한글예시

const [,,thirdAnimal] = ["캥거루", "웜뱃", "코알라"];

console.log(thirdAnimal); // 코알라

const [,b,] = ["캥거루", "웜뱃", "코알라"];

console.log(b); // 웜뱃

const [,c] = ["캥거루", "웜뱃", "코알라"];

console.log(c); // 웜뱃

const [d] = ["캥거루", "웜뱃", "코알라"];

console.log(d); // 캥거루

 

 

5. 콤마를 사용한 배열 구조 분해

 

 

firstResort, thirdResort 값만 변수에 저장하고 firstResort를 출력

 

3개의 배열 값을 다 저장하고 2번째 배열 값만 출력

// More Array Destructuring

var [firstResort,secondResort,thirdResort] = ["Kirkwood", "Squaw", "Alpine"]

console.log(thirdResort)

 

참고자료

러닝 리액트(Learning React), 알렉스 뱅크스, 한빛미디어 (2021)

728x90
반응형