디스트럭처링 할당 ( 구조 분해 할당 )

구조화된 배열과 같은 이터러블 또는 객체를 디스트럭처링하여 1개 이상의 변수에 개별적으로 할당하는 것을 말한다. 
const arr = [4,5,6];
const [six, five, four] = arr;
console.log(four, five, six); // 6 5 4 
// 배열 디스트럭처링 할당의 대상은 이터러블이어야하며,
// 할당 기준은 배열의 인덱스다.

const [a,b] = [1,2];
const [c,d] = [3];
const [e,f] = [5,6,7];
console.log(a,b); // 1, 2
console.log(c,d); // 1 undefiend
console.log(e,f); // 1, 2
// 요소 개수가 반드시 일치할 필요는 없다. 

const [x, ...y] = [1,2,3];
console.log(x,y);
// Rest 요소 ...을 사용해서 가능. 

const user = { 
  firstName: 'Taku', 
  lastName: 'Oh'
}
const { lastName, firstName } = user;
console.log(firstName, lastName); // Taku Oh
// 객체 디스트럭처링은 할당 기준이 프로퍼티 키다. 

const name = { 
  firstName: 'jeongmin', 
  lastName: 'lee',
  address : {
    hometown: 'cheonan'
  }};
const { firstName: fN, lastName: lN, address:{hometown}} = name;
console.log(fN, lN, hometown);
// 객체의 프로퍼티 키와 다른 변수 이름으로 프로퍼티 값을 할당 받으려면 이렇게 작성하면 된다. 
// 중첩 객체를 빼려면 프로퍼티 값과 그안에 프로퍼티를 대괄호로 감싸준다.

 

Set

Set 객체는 중복되지 않는 유일한 값들의 집합이다. Set 수학적 집합을 구현하기 위한 자료구조다.

 

배열과의 차이 

구분 배열  Set 객체 
동일한 값을 중복하여  포함할 수 있다. O X
요소 순서에 의미가 있다. O X
인덱스로 요소에 접근할 수 있다. O X
const set1 = new Set([1,2,3,3]);
// Set은 new 연산자와 함께 호출한다. 
console.log(set1);
console.log(set1.size) // size 메소드
console.log(set1.add(4)); // add 메소드
console.log(set1.has(2)); // has 메소드
set1.delete(3); // delete 메소드
console.log(set1);
set1.clear(); // clear 메소드
console.log(set1);

const set2 = new Set(['a','b','c','d'])
set2.forEach((v,v2,self) => {
  console.log(v,v2,self);
})
// a a Set(4) { 'a', 'b', 'c', 'd' }
// b b Set(4) { 'a', 'b', 'c', 'd' }
// c c Set(4) { 'a', 'b', 'c', 'd' }
// d d Set(4) { 'a', 'b', 'c', 'd' }

 

Map

Map 객체는 키와 값의 쌍으로 이루어진 컬렉션이다. 객체와 유사하지만 차이가 있다. 
구분 객체 Map 객체
키로 사용할 수 있는 값 문자열 또는 심벌 값 객체를 포함한 모든 값
이터러블 X O
요소 개수 확인 Object.keys(obj).length  
const map = new Map([['key1', 'value1'],['key2', 'value2']]);

console.log(map); //Map(2) { 'key1' => 'value1', 'key2' => 'value2' }
console.log(map.size); // size 메소드
console.log(map.set('key3','value3')); // set 매소드
console.log(map.get('key2')) // get 메소드
console.log(map.has('key3')) // has 메소드
map.delete('key2') // delete 메소드
console.log(map);
// Map(2) { 'key1' => 'value1', 'key3' => 'value3' }
map.clear(); // clear 메소드
console.log(map); // Map(0) {}

 

 

 

후기

- 클린코드를 만드는데 정말 많이 필요하고 쓰임새가 정말 많은 디스트럭쳐링.. 너무 늦게 알게되었다 싶다..

   지금까지 해온 코드, 프로젝트 리팩토링하면 100줄은 짧아질거같다.. 

 

- Set 과 Map은 알고리즘 수업때 먼저 들었었는데, Set이 중첩을 방지해주는 착한 객체로만 알고 있었는데,

   수학적 집합을 위한 약간의 목적성이 있는 객체였다는거를 처음알았다.

 

- Map과 일반객체와의 차이점을 확실히 넘어가볼 수 있어서 좋았다. 스터디하면서 형이 링크를 추천해준게 있는데 정리를 해보자면 

 

1. The construction is of course different

    ( 구조적인 차이 )

 

2. Keys on objects are strings, on maps keys are of any type

    ( 객체의 키값은 문자열, 맵의 키는 모든 데이터 타입이 된다. )

 

3. Object maps inherit unwanted keys from the prototype 

    (  맵 객체는 프로토타입으로부터 원치 않는 키를 상속 받는다. )

 

4. Maps preserve the order of their keys, objects do not

    (  키 값의 순서 보존하고, 객체는 순서가 없다. )

 

5. Maps offer a nicer interface for accessing entries

    ( 엔트리 접근하기 위한 훨씬 인터페이스가  좋다. )

 

6. Objects require helpers functions for accessing the key-values pairs

    ( 객체는 key-values 쌍에 접근하기 위한 보조 함수가 필요하다. ) 

 

7. JSON offers support for objects but not for maps

     ( JSON은 객체를 지원하지만 맵은 안함 )

 

https://medium.com/dailyjs/7-differences-between-objects-and-maps-in-javascript-bc901dfa9350

 

7 Differences between Objects and Maps in JavaScript

Objects and maps are both dynamic collections of key-value pairs.

medium.com