[Destructuring] 배열 또는 객체 내 원소를 직관적으로 이용하기

2020. 5. 23. 18:25컴퓨터언어/Vanilla JS

728x90
반응형

배열은 [0], [100]처럼 숫자로 인덱싱을 하고,

객체는 myObj.name, myObj["name"]처럼 key로 인덱싱을 한다.

 

인덱싱은 분명 그 자체로 빠르고 직관적인 탐색이지만,

코드량이 많아지거나 협업을 할 때 갑자기 [0]이 나타났다면 코드의 흐름을 한눈에 파악하기 어려울 수 있다.

 

게다가 배열 안에 또다른 배열이 있거나, 객체 안에 또다른 객체가 있거나, 객체 안에 배열이 있거나 등등 데이터가 중첩되고(nested) 복잡해진다면 더 말할 것 없다.

 

이럴 때 기존처럼 단순히 숫자나 key로 접근하는 것이 아니라, 언제봐도 직관적으로 이게 어떤 값에 접근하는지를 나타내는 커스텀 인덱스가 있으니, 이것이 바로 Destructuring이다.

 


Destructuring은 단어 그대로 구조를 해체하는 것으로, 원래 상태의 배열/객체의 원소 각각을 변수에 할당하는 것이다.

const students = [
  { type: "freshman", goal: "play" },
  { type: "sophomore", goal: "play more" },
  { type: "junior", goal: "graduate" },
  { type: "senior", goal: "get a job" },
];

// 기존
console.log(students[0].goal); // play

// Destructuring
const [freshman, sophomore, junior, senior] = students;
const {type, goal} = freshman;

console.log(goal); // play

*배열의 Destructuring은 원래 인덱스가 숫자였기 때문에 커스텀 인덱스를 임의로 지어도 되지만,

객체의 Destructuring은 원래 key값이 name이었다면 커스텀 인덱스도 name으로 만들어야 한다. 대신 위에서처럼 서로 다른 객체에 대해 혼동을 피하기 위해 콜론을 사용하여 별명을 지어줄 수 있다.

const [freshman, sophomore, junior, senior] = students;
const {type: freshmanType, freshmanGoal} = freshman;

console.log(freshmanGoal); // play

만약 기존 객체에 해당 key 자체가 없어서(undefined) 기본값을 세팅하고 싶다면, =을 이용하여 key는 물론 그 value까지 할당할 수 있다.

=를 사용할 때는 콜론이 필요없고, 바로 커스텀 key로 작명이 가능하다.

const students = [
  { type: "freshman" },
  { type: "sophomore", goal: "play more" },
  { type: "junior", goal: "graduate" },
  { type: "senior", goal: "get a job" },
];
const [freshman, sophomore, junior, senior] = students;
const {type: freshmanType, freshmanGoal="just play dude"} = freshman;

console.log(freshmanGoal); // just play dude

 

*기본값 세팅을 쓰는 이유는, 이 역시 JSON으로 데이터를 받아왔을 때 만약 해당 key가 비어있다면 앱이 crash날 수 있기 때문에 이를 대비하기 위함이다.


 

그런데 만약 객체 안에 객체가 중첩되어 있다면, 그 안의 값을 어떻게 효율적으로 불러올 수 있을까?

위에서 별명을 지을 때 콜론을 사용했었음을 기억할 것이다.

간단하다. 이번에는 사용할 별명이 아닌, 그 내부 객체의 key를 {}와 함께 그대로 적어주면 되는것이다.

const students = [
  { type: "freshman", goal: "play" },
  { type: "sophomore", goal: "play more" },
  { type: "junior", goal: "graduate" },
  { type: "senior", goal: "get a job", requirements: { toeic: 900, voluntary: 5} },
];
const [freshman, sophomore, junior, senior] = students;
const {type: freshmanType, goal: freshmanGoal, requirements: { toeic, voluntary } } = senior;

console.log(toeic); // 900

Destructuring은 쉽게 말해 데이터 이용의 커스터마이징이다.

이는 특히 서버에서 API로 데이터를 받아올 때 빛을 발하는데, 보통 데이터는 객체로 되어있는 JSON 형태로 되어있기 때문이다.

우리는 JSON을 받아온 후, 원래 있던 key값을 내가 원하는 이름으로 바꿈으로써, 내가 혹은 우리팀이 유지보수하기 쉬운 방향으로 이끌어갈 수 있다.

 

 

728x90
반응형