IT & Dev.

구조 분해 할당 (destructuring)

시고르빙봉 2023. 10. 22. 15:53
728x90
반응형

구조 분해 할당 (Destructuring) 을 사용하면 배열이나 객체의 값을 쉽게 접근하고 변수에 할당할 수 있다.

 

배열

const array = [1, 2, 3];
const [a, b] = array;

console.log(a); // 1
console.log(b); // 2
console.log(array); // [1, 2, 3]
 

객체

const myObj = {
	name: "Tom",
	age: 30
}

const {name} = myObj;
console.log(name); // Tom
console.log(age); // undefined
console.log(myObj); // {name: "Tom", age: 30}
 

함수 매개변수

함수가 객체를 포함하는 매개변수를 수락하는 경우, 객체 프로퍼티를 “꺼내어’” 로컬 범위 변수(즉, 함수 본문 내에서만 사용할 수 있는 변수)로 사용할 수 있도록 함수를 구조분해 할당 할 수 있다.

ex) 1.

// before
const printName = (personObj) => {
	console.log(personObj.name);
}
printName({name:"Tom", age: 30}); // Tom

함수 안에 있는 name만 출력하고 싶지만 함수에 완전한 personObj를 보내고 있다. 문제가 되지 않지만, 함수 내부에서 객체의 name (personObj.name)을 호출하고 있기 때문에 아래와 같이 구조분해 할당을 할 수 있다. 

// after
const printName({name}) => {
	console.log(name);
}
printName({name: "Tom", age: 30}); // Tom

name 프로퍼티를 가져와 name이라는 이름의 인수에 저장하여 함수 본문에서 사용할 수 있다.


ex) 2.

function storeOrder(order) {
  localStorage.setItem('id', order.id);
  localStorage.setItem('currency', order.currency);
}

storeOrder 함수 본문 내부의 "점 표기법"을 통해 order 프로퍼티에 접근하지 않고, 다음과 같이 구조분해 할당을 사용할 수 있다.

 

function storeOrder({id, currency}) { 
  localStorage.setItem('id', id);
  localStorage.setItem('currency', currency);
}

구조분해 할당 구문은 상수나 변수를 수동으로 생성하지 않을 뿐, 들어오는 객체(즉, storeOrder 에 인수로 전달된 객체)에서 id와 currency 를 "꺼내어" 사용한다.

이 예제에서 storeOrder 는 여전히 하나의 매개변수만 받는다는 점이 중요하다. 매개변수는 두 개가 아니라, 하나의 매개변수, 즉 내부적으로 구조분해 할당된 객체만 받는다.

함수는 여전히 다음과 같이 호출된다.

storeOrder({id: 5, currency: 'USD', amount: 15.99}); // 1개의 매개변수 / 값!
728x90
반응형