
함수에 객체나 배열을 전달해야 하는 경우가 생기곤 한다. 가끔은 객체나 배열에 저장된 데이터 전체가 아닌 일부만 필요한 경우가 생기기도 한다.
이럴 때 객체나 배열을 변수로 '분해’할 수 있게 해주는 특별한 문법인 구조 분해 할당(destructuring assignment) 을 사용할 수 있다.
함수의 매개변수가 많거나 매개변수 기본값이 필요한 경우 등에서 사용한다.
배열 구조 본해 변수에 값을 할당하는 기본 방법
var foo = ['one', 'two', 'three'];
var [one, two, three] = foo;
console.log(one); // "one"
console.log(two); // "two"
console.log(three); // "three"
foo에 one, two, three를 각각 저장한 후, 변수 one two three에 구조분해로 할당되어 출력되는 것을 확인 할 수 있다.
변수 선언과 할당을 분리하여 배열 구조분해 할당을 할 수 있다.
var a, b;
[a, b] = [1, 2]
console.log(a); // 1
console.log(b); // 2
할당하고자 하는 변수의 개수가 분해하고자 하는 배열의 길이보다 크더라도 에러가 발생하지 않는다. 할당할 값이 없으면 undefined로 취급되기 때문.
let [firstName, surname] = [];
alert(firstName); // undefined
alert(surname); // undefined
= 을 이용하면 할당할 값이 없을 때 기본으로 할당해 줄 값인 기본값(default value)을 설정할 수 있습니다.// 기본값
let [name = "Guest", surname = "Anonymous"] = ["Julius"];
alert(name); // Julius (배열에서 받아온 값)
alert(surname); // Anonymous (기본값)
var [a, b] = [1, 3];
[a, b] = [b, a];
console.log(a); // 3
console.log(b); // 1
두개의 값 교환을 배열 구조분해를 사용하면 한줄로 표현이 가능하다
쉼표를 사용하면 필요하지 않은 배열 요소를 버릴 수 있다.
// 두 번째 요소는 필요하지 않음
let [firstName, , title] = ["Julius", "Caesar", "Consul", "of the Roman Republic"];
alert( title ); // Consul
두 번째 요소는 생략되었지만, 세 번째 요소는 title이라는 변수에 할당된 것을 확인할 수 있다. 할당할 변수가 없기 때문에 네 번째 요소 역시 생략되었다.
...(전개연산자)를 이용해 나머지 배열을 변수에 할당이 가능합니다.
var [a, ...b] = [1, 2, 3];
console.log(a); // 1
console.log(b); // [2, 3]
var a = { p: 42, q: true };
var { p, q } = a;
console.log(p); // 42
console.log(q); // true
var { a, b } = { a:1, b:2 };
console.log(a); // 1
console.log(b); // 2
var a = { p: 42, q: true };
var { p: foo, q: bar };
console.log(foo); // 42
console.log(bar); // true
var metadata = {
title: 'Scratchpad',
translations: [
{
locale: 'de',
localization_tags: [],
last_edit: '2014-04-14T08:43:37',
url: '/de/docs/Tools/Scratchpad',
title: 'JavaScript-Umgebung',
},
],
url: '/en-US/docs/Tools/Scratchpad',
};
var {
title: englishTitle,
translations: [{ title: localeTitle }],
} = metadata;
console.log(englishTitle); // "Scratchpad"
console.log(localeTitle); // "JavaScript-Umgebung"
배열이나 객체의 요소를 반복하면서 구조 분해를 사용할 수 있고, 데이터를 효과적으로 처리하는 데 유용하다.
var people = [
{
name: 'Mike Smith',
family: {
mother: 'Jane Smith',
father: 'Harry Smith',
sister: 'Samantha Smith',
},
age: 35,
},
{
name: 'Tom Jones',
family: {
mother: 'Norah Jones',
father: 'Richard Jones',
brother: 'Howard Jones',
},
age: 25,
},
];
for (var {
name: n,
family: { father: f },
} of people) {
console.log('Name: ' + n + ', Father: ' + f);
}
// "Name: Mike Smith, Father: Harry Smith"
// "Name: Tom Jones, Father: Richard Jones"
함수의 매개변수를 구조 분해하여 원하는 속성을 바로 추출할 수 있고, 객체에서 특정 속성을 가져와 사용할 때 매우 편리하다.
var user = {
id: 42,
displayName: 'jdoe',
fullName: { firstName: 'John', lastName: 'Doe' },
};
function userId({ id }) {
return id;
}
console.log(userId(user)); // 42
변수 이름을 동적으로 결정해야 할 때, 객체의 속성 이름을 변수로 사용할 수 있습니다. 이것은 계산된 속성 이름(Computed Property Names)의 활용 예시
let target = "z";
let { [target]: foo } = { z: "bar" };
console.log(foo); // "bar"