[JS DeepDive] 36. 구조 분해 할당

HyeLin·2022년 7월 24일
1
post-thumbnail

구조 분해 할당

구조화된 배열과 같은 이터러블 또는 객체를 destructuring하여 1개 이상의 변수에 개별적으로 할당하는 것을 말한다. 필요한 값만 추출하여 변수에 할당할 때 유용하다.

🟡 배열

const arr = [1, 2, 3]

// 변수 one, two, three를 선언하고 배열 arr을 구조 분해 할당
// 이때 할당 기준은 배열의 인덱스
const [one, two, three] = arr 
console.log(one, two, three) // 1, 2, 3

🟡 객체

객체의 각 프로퍼티를 객체로부터 추출하여 1개 이상의 변수에 할당한다. 이때 객체 구조분해할당의 대상은 객체여야 하며, 할당 기준은 프로퍼티 키다. 즉, 순서는 의미 없고 선언된 변수 이름과 프로퍼티 키가 일치하면 할당된다.

const user = { first: 'hyerin', last: 'seol'}
const { last, first } = user

console.log(first, last) //hyerin seol

function print(todo){
console.log(`할일 ${todo.content}${todo.completed ? '완료': '비완료'}상태입니다`)
}

print({id: 1, content: 'HTML', completed: true}) // 할일 HTML은 완료 상태입니다

const user = {
  name: 'seol',
  address: {
  	zip: '000',
    city: 'seoul'
  }
}

// address 프로퍼티 키로 추출하고, 이 객체의 city 프로퍼티 키로 값을 추출한다
const {address: {city}} = user
console.log(city) // 'seoul'
profile
개발자

0개의 댓글