Study/JavaScript(Clean code)

[JavaScript][clean-code] Object Destructuring (객체 구조 분해 할당)

갈푸라떼 2022. 6. 7. 13:57

* Object Destructuring (객체 구조 분해 할당)

 

* 생성자 함수로 보는 예시

function Person(name, age, location) {
  this.name = name;
  this.age = age;
  this.location = location;
}

const hyeonwoo = new Person('hyeonwoo', undefined, 'korea');

- 기존에는 값을 안넣을경우 undefined를 작성해줘야한다.

 

* 객체 구조 분해 할당

function Person( name, { age, location }) {
  this.name = name;
  this.age = age;
  this.location = location;
}

const pocoOptions = {
  age : 30,
  location : 'korea',
}

const poco = new Person('poco', pocoOptions);
  • 객체에 할당에 대한 순서를 지키지 않아도 된다. 그리고 넣지않는 값에 대해서 안넣어도된다.
  • 넣지 않는 값에는 nullish연산자를 사용해준다.
  • 그러면 명확하게 구분이 되어서 좋다.
  • 인자가 3개 이상일때는 객체로 구성하는것이 좋다.
  • 위의 예시는 첫번째 인자는 필수로 받고 나머지는 option으로 받는다.
  • 따라서 name은 필수라는것을 명시적으로 알 수 있다.

* 다른 예시

const orders = ['First', 'Second', 'Third'];

const st = orders[0];
const rd = orders[2];

const [first, ,third] = orders

console.log(first);
console.log(third);
const orders = ['First', 'Second', 'Third'];

const { 0 :st2, 2: rd2 } = orders

console.log(st2)
console.log(rd2)
  • 배열을 객체로도 사용이 가능하다.
  • JavaScript에서는 배열이 객체로도 취급된다.
  • 수많은 배열의 요소들을 간단하게 분리할때는 편리하게 사용이 가능하다.