[JavaScript] Es6 신문법 Destructuring (구조분해할당)

qwe8851·2022년 10월 13일
0

📚 JavaScript

목록 보기
20/53

회사사람이 공유해준 코드를 보다가 궁금한 점이 있어서 찾아봤다.


🤔 배열이라면?

# Before

const arr = ["a", "b", "c", "d"];

const first = arr[0];
const second = arr[1];
const third  = arr[2];
const fourth = arr[3];

console.log(first, second, third, fourth)

원래대로라면 배열의 값을 각각의 변수에 담기 위해서는 위 코드처럼 써야 한다.

# After

const arr = ["a", "b", "c", "d"];
const [first, second, third, fourth] = arr

console.log(first, second, third, fourth)

이렇게 써줄 수 있다.
왼쪽부터 배열의 순서대로 할당된다.

📎 이런식으로도 가능

let a, b, c
[a, b, c] = ["a", "b", "c"];

console.log(a, b, c)




🤔 객체라면?

# Before

const OBJ = {name:"kim", age:23}

const name = OBJ.name
const age = OBJ.age

console.log(name, age)

# After

const OBJ = {name:"kim", age:23}

const {name, age} = OBJ

console.log(name, age)

구조분해할당을 이용하면 이런식으로 쓸 수 있다.

✔️ 배열과의 다른점은 변수로 지정한 3행에서 객체의 순서대로 변수에 담는데 아닌, 객체의 프로퍼티를 빼는 것이다.

그렇기 때문에

const OBJ = {name:"kim", age:23}

const {a, b} = OBJ

console.log(a, b)

이런식으로 쓰면 undefined를 출력함.

중첩된 객체라면?

const event = {
  target:{
    name:"kim",
    age:23
  }
}

const {target : {name}} = event

console.log(name)

이런식으로 꺼내줄 수 있다.
(필요한 부분만 꺼내는것도 가능하므로 위에서 name만 꺼냄)

중첩이 여러개 겹친다면??

const event = {
  target:{
    name:"kim",
    age:23,
   another:{
      help:{
        memo:{
          listOne:"힘들다"
        }
      }
    } 
  }
}

const {target : {another:{help:{memo:{listOne}}}}} = event

console.log(listOne)

이렇게도 쓸 수 있다..

profile
FrontEnd Developer with React, TypeScript

0개의 댓글