디스트럭처링
배열 디스트럭처링 (Array destructuring)
let x, y, z;
[x, y] = [1, 2];
console.log(x, y); // 1 2
[x, y] = [1];
console.log(x, y); // 1 undefined
[x, y] = [1, 2, 3];
console.log(x, y); // 1 2
[x, , z] = [1, 2, 3];
console.log(x, z); // 1 3
// 기본값
[x, y, z = 3] = [1, 2];
console.log(x, y, z); // 1 2 3
[x, y = 10, z = 3] = [1, 2];
console.log(x, y, z); // 1 2 3
// spread 연산자
[x, ...y] = [1, 2, 3];
console.log(x, y); // 1 [ 2, 3 ]
const today = new Date();
const formattedDate = today.toISOString().substring(0, 10);
const [year, month, day] = formattedDate.split('-');
console.log([year, month, day]); // [ '2018', '05', '05' ]
객체 디스트럭처링 (Object destructuring)
// ES6 Destructuring
const obj = { firstName: 'Ungmo', lastName: 'Lee' };
const { firstName, lastName } = obj;
console.log(firstName, lastName); // Ungmo Lee
const todos = [
{ id: 1, content: 'HTML', completed: true },
{ id: 2, content: 'CSS', completed: false },
{ id: 3, content: 'JS', completed: false }
];
// todos 배열의 요소인 객체로부터 completed 프로퍼티만을 추출한다.
const completedTodos = todos.filter(({ completed }) => completed);
console.log(completedTodos); // [ { id: 1, content: 'HTML', completed: true } ]
const person = {
name: 'Lee',
address: {
zipCode: '03068',
city: 'Seoul'
}
};
const { address: { city } } = person;
console.log(city); // 'Seoul'