destructuring assignment (오브젝트)

ES
비고
오브젝트 프롭 해체 할당
Tags
object
해체할당
 
 

원하는 프로퍼티만 추출하기

destructuring assignment (배열)
배열에서는 해체할당 시 필요없는 부분을 건너뛰고 원하는 부분만 추출하려면 ,로 순서를 건너 뛰어야 했다.
하지만 오브젝트에서는 그럴 필요 없이 진짜 필요한 프로퍼티의 이름만으로 바로 추출 가능하다.
const testObject = {one:1, two:2, three:3, four:4, five:5}; const {one, four} = testObject;
 

객체 자체가 undefined 일 수 있을 때 구조분해 꿀팁

  • 객체 자체가 undefined 일 수 있는 경우에는, 프로퍼티가 없다는 에러가 뜨는 타입 이슈가 있다.
  • 이 경우에는 객체 자체를 구조 분해 하여 새로운 객체를 만들어서 헷징할 수 있다.
type test = { one: number; two: number; three: number; }; const testFunction = ({data}:{data?: test}):void=>{ // const {one, three} = data; // data 오브젝트 자체가 undefined 일 수 있어서 프롭 없다고 에러 const {one, three} = {...data}; // 오브젝트가 undefined라면 one, three에 각각 undefined가 들어가고, 있다면 값이 들어감 console.log("one, three", one, three); }
type test = { melong:{ hi: 'hi', hello: 'hello' } }; const testFunction = ({data}:{data?: test}):void=>{ // const {hi, hello} = data?.melong; // melong 오브젝트 자체가 undefined 일 수 있어서 프롭 없다고 에러 const {hi, hello} = {...data?.melong}; // 오브젝트가 undefined라면 hi,hello에 각각 undefined가 들어가고, 있다면 값이 들어감 console.log("hi, hello", hi, hello); }