[JavaScript] 구조 분해 할당

우기·2023년 3월 25일
0
post-thumbnail

객체와 배열은 자바스크립트에서 가장 많이 쓰이는 자료 구조다.

키를 가진 데이터 여러 개를 하나의 엔터티에 저장할 땐 객체를, 컬렉션에 데이터를 순서대로 저장할 땐 배열을 사용한다.

개발을 하다 보면 함수에 객체나 배열을 전달해야 하는 경우가 생긴다. 또한 객체나 배열에 저장된 데이터 전체가 아닌 일부가 필요한 경우가 생긴다.

이럴 때 객체나 배열을 변수로 '분해'할 수 있게 해주는 특별한 문법인 구조 분해 할당을 사용할 수 있다.

이 외에도 함수의 매개변수가 많거나 매개변수 기본값이 필요한 경우 등에서 구조 분해(destructuring)는 그 진가를 발휘합니다.

✅ 배열 분해하기


split

let [firstName, surname] = "Bora Lee".split(' ');

💡 '분해(destructuring)'는 '파괴(destructive)'를 의미하지 않습니다.

구조 분해 할당이란 명칭은 어떤 것을 복사한 이후에 변수로 '분해(destructurize)'해준다는 의미 때문에 붙여졌다. 이 과정에서 분해 대상은 수정 또는 파괴되지 않는다.

'…'로 나머지 요소 가져오기

let [name1, name2, ...rest] = ["Julius", "Caesar", "Consul", "of the Roman Republic"];

alert(name1); // Julius
alert(name2); // Caesar

// `rest`는 배열입니다.
alert(rest[0]); // Consul
alert(rest[1]); // of the Roman Republic
alert(rest.length); // 2

기본값

=을 이용하면 할당할 값이 없을 때 기본으로 할당해 줄 값인 '기본값(default value)'을 설정할 수 있다.

// 기본값
let [name = "Guest", surname = "Anonymous"] = ["Julius"];

alert(name);    // Julius (배열에서 받아온 값)
alert(surname); // Anonymous (기본값)

✅ 객체 분해하기


let options = {
  title: "Menu",
  width: 100,
  height: 200
};

let {title, width, height} = options;

alert(title);  // Menu
alert(width);  // 100
alert(height); // 200

프로퍼티 options.titleoptions.width, options.height에 저장된 값이 상응하는 변수에 할당된 것을 확인할 수 있다.

let options = {
  title: "Menu",
  width: 100,
  height: 200
};

// { 객체 프로퍼티: 목표 변수 }
let {width: w, height: h, title} = options;

// width -> w
// height -> h
// title -> title

alert(title);  // Menu
alert(w);      // 100
alert(h);      // 200

프로퍼티 width를 변수 w에, 프로퍼티 height를 변수 h에 저장했다.
프로퍼티 title은 동일한 이름을 가진 변수 title에 저장된다.

let options = {
  title: "Menu"
};

let {width: w = 100, height: h = 200, title} = options;

alert(title);  // Menu
alert(w);      // 100
alert(h);      // 200

콜론과 할당 연산자를 동시에 사용할 수도 있다.

✅ 중첩 구조 분해


  • 객체나 배열이 다른 객체나 배열을 포함하는 경우, 좀 더 복잡한 패턴을 사용하면 중첩 배열이나 객체의 정보를 추출할 수 있다.

  • 이를 중첩 구조 분해(nested destructuring)라고 부른다.

let options = {
  size: {
    width: 100,
    height: 200
  },
  items: ["Cake", "Donut"],
  extra: true
};

// 코드를 여러 줄에 걸쳐 작성해 의도하는 바를 명확히 드러냄
let {
  size: { // size는 여기,
    width,
    height
  },
  items: [item1, item2], // items는 여기에 할당함
  title = "Menu" // 분해하려는 객체에 title 프로퍼티가 없으므로 기본값을 사용함
} = options;

alert(title);  // Menu
alert(width);  // 100
alert(height); // 200
alert(item1);  // Cake
alert(item2);  // Donut

✦ Reference

profile
개발 블로그

0개의 댓글