PROGRAMMING/Javascript

[Javascript] 구조 분해 할당 배열, 객체

seulda 2021. 8. 21. 02:38
728x90

 

구조 분해 할당(destructuring assignment) 

객체나 배열을 변수로 분해해주는 문법

 

배열 분해하기

let arr = ["Hello", "World"]

let [one, two] = arr;
// 위 line은 아래 두 줄과 같은 의미
// let one = arr[0];
// let two = arr[1];

console.log(one);  // Hello
console.log(two);  // World

 

  • 쉼표를 사용하여 요소를 무시할 수도 있다.
let [one, , what] = ["Hello", "World", "Javascript", "so funny"];

console.log( what ); // Javascript

 

  • 객체 프로퍼티에도 사용이 가능하다.
let block = {};
[block.first, block.second] = "Hello World".split(' ');

console.log(block.first); // Hello

 

  • 두 변수 값의 교환도 가능하다.
let one = "Hello";
let two = "World";

[one, two] = [two, one];

console.log(`${one} ${two}`); // World Hello

 

  • ...을 사용하여 나머지 요소를 배열로 받아올 수 있다.
let [one, two, ...etc] = ["Hello", "World", "Javascript", "so funny"];

console.log(one); // Hello
console.log(two); // World

console.log(etc[0]); // Javascript
console.log(etc[1]); // so funny
console.log(etc.length); // 2

 

  • 기본으로 할당해줄 값을 지정할 수 있으며, 값이 없을 경우 undifined로 취급된다.
let [one = "one", two = "two", three] = ["Hello"];

console.log(one); // Hello (배열에서 받아온 값)
console.log(two); // two (기본값)
console.log(three); // undefined

 

 


 

객체 분해하기

// 기본 구조
// let {var1, var2} = {var1:…, var2:…}

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

let {title, width, height} = options;

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

 

  • 객체 프로퍼티의 순서와 동일하지 않아도 된다. 객체 프로퍼티를 프로퍼티 키와 다른 이름을 가진 변수에 저장할 수 있다.
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

 

  • 프로퍼티에도 기본값을 지정할 수 있으며, 목표변수와도 함께 사용이 가능하다.
let options = {
  title: "Menu"
};

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

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

 

  • 객체 내에서 원하는 프로퍼티의 값만 가져올 수 있다.
et options = {
  title: "Menu",
  width: 100,
  height: 200
};

// title만 변수로 뽑아내기
let { title } = options;

alert(title); // Menu

 

  • ...을 사용하여 나머지 패턴 구현이 가능하다 : 사용시 지원이 안되는 브라우저도 있으니 확인할 것
let options = {
  title: "Menu",
  height: 200,
  width: 100
};

// title = 이름이 title인 프로퍼티
// rest = 나머지 프로퍼티들
let {title, ...rest} = options;

// title엔 "Menu", rest엔 {height: 200, width: 100}이 할당됩니다.
alert(rest.height);  // 200
alert(rest.width);   // 100

 


중첩 구조 분해(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

 

728x90