본문 바로가기

자바스크립트의 정석 🟡

자바스크립트 - Destructuring assignment

참고자료: 인프런 자바스크립트 초급강의

 

Javascript ES6+ 제대로 알아보기 - 초급 - 인프런 | 강의

ES6+ 제대로 알아보기 강좌는 Javascirpt의 ES6 및 이후의 표준 ECMAScript 명세에 대하여 이론을 바탕으로 ES5와 달라진 점 및 개념과 동작 원리를 깊이 있게 알려드립니다., Javascript ES6+는 뭐가 다를까?

www.inflearn.com

 

1. 해체할당

1-1. 배열 할당 

var colors = ['red', 'white', 'orange']
var first = colors[0]
var second = colors[1]
var third = colors[2]
console.log(first, second, third)

//해체할당
const colors = ['red', 'white', 'orange']
const [first, second, third] = colors
console.log(first, second, third)

응용해서 

let [ , , third] = colors;
let[ , second] = colors;

이렇게도 가능, 자기가 원하는 몇 번째 인자만

 

그럼 만약

const [ , , third, fourth] = colors;
console.log(fourth); //undefined

매칭할게 없으면 undefined로 출력된다 !

 

 

 

나머지 연산으로도 가능

const arr = [1, 2, 3, 4, 5]
const [ a, ...b ] = arr
const [ , , ...c ] = arr

 

 

나아가서,

const [c, d = c * 2] = [5]
console.log(c, d);

//result
c: 5 d: 10
const [e = f, f] = [undefined, 10]

위에 코드는 TDZ에 걸림. e선언할 때, f선언 안됐는데 인용되고 있으니.

 

const arr = [1, [2, [3, 4], 5], 6]
const [a, [b, [ , c], ], d] = arr
console.log(a, b, c, d)

똑같은 모양으로 적으면 다 추출돼 !

 

 

 

 

- 두개 인자 값 바꾸고 싶을 때

let a = 10;
let b = 20;
[a, b] = [b, a]

 

 

1-2. 객체 할당  ⭐⭐⭐⭐⭐

 

const iu = {
  name : '아이유',
  age : 25,
  gender : 'female'
}

const {
  name,
  age,
  gender
} = iu

console.log(name, age, gender)

조금 어렵게 간다면,

 

const loginInfo = {
  device: {
    createdAt: '2017-12-06T00:14:04+0000',
    deviceId: '0000000000004Vx',
    deviceType: 'desktop'
  },
  user: {
    createdAt: '2017-03-08T18:00:28+0000',
    email: 'power4ce@gmail.com',
    name: '정재남',
    nickname: 'gomugom',
    phoneNumber: '010-9185-9155'
  }
}


//객체 해체
const {
  device: {
  	createdAt,
    deviceId
  },
  user: {
    name,
    nickname,
    phoneNumber: phone
  }
} = loginInfo

 

 

 

- default parameter와 연동 가능

const phone = {
  name : 'iPhone',
  color : undefined
}

const {
  name: n,
  version: v = '6+',
  color: c = 'silver'
} = phone
console.log(n, v, c)

//result
iPhone 6+ silver

iPhone은 그대로 출력

version 인자가 없어서 default 값인 6+ 출력

color는 undefined이기 때문에 default 값 silver 출력

 

 

 

 

실제 현업에서 많이 사용하는 예

const deliveryProduct = {
  orderedDate: '2018-01-15',
  estimatedDate: '2018-01-20',
  status: '배송중',
  items: [
    {name: '사과', price: 1000, quantity: 3},
    {name: '배', price: 1500, quantity: 2},
    {name: '딸기', price: 2000, quantity: 4}
  ]
}

const {
  estimatedDate: esti,
  status,
  items: [ , ...products]
} = deliveryProduct
console.log(esti, status, products)

코드 의미)

estimateDate 이름 너무 길어 esti로 바꿀래

status 다 가져와

item은 첫번째 프로퍼티 제외하고는 나머지는 다 products라고 칭할래

 

 

 

끝!