다음 예제를 보며 Destructing
를 이해해보도록 하자 .
let superman = {
type: "Hero",
hourlyPayment: 1000,
};
// es6 이전
let type = superman.type;
let hourlyPayment = superman.hourlyPayment;
// es6
// Destructing
const { type, hourlyPayment } = superman;
console.log(type); // Hero
console.log(hourlyPayment); // 1000
두 번째 예시는 약간 다르다. 함꼐 보도록 하자.
let employee = {
name: "Superman",
type: "Hero",
hourlyPayment: 1000,
};
// let type = superman.type;
// let hourlyPayment = superman.hourlyPayment;
const { name, type, hourlyPayment } = employee;
console.log(type); // Hero
console.log(hourlyPayment); // 1000
function priceOfHero(arg) {
console.log(`${arg.name} is a ${arg.type} employee with hourly payment of ${arg.hourlyPayment}`)
};
priceOfHero(employee); // Superman is a Hero employee with hourly payment of 1000
위의 priceOfHero 함수를 Destructing
을 이용하여 다음과 같이 리팩토링 할 수 있다.
function priceOfHero(arg) {
const { name, type, hourlyPayment } = arg;
console.log(`${name} is a ${type} employee with hourly payment of ${hourlyPayment}`)
};
// 혹은 다음처럼도 가능하다.
function priceOfHero({ name, type, hourlyPayment }) {
console.log(`${name} is a ${type} employee with hourly payment of ${hourlyPayment}`)
};
다음 코드를 보도록 하자.
let employees = [
{
name: "Superman",
type: "Hero",
payments: ['1000/hr', '10000/day', '50000/week'],
},
{
name: "Batman",
type: "Hero",
payments: ['2000/hr', '10000/day', '50000/week'],
},
{
name: "Ironman",
type: "Hero",
payments: ['3000/hr', '10000/day', '50000/week'],
},
];
// es6 이전
var payments1 = employees[0].payments;
console.log(payments1); // ['1000/hr', '10000/day', '50000/week']
// es6
const [{payments}, b, c] = employees;
console.log(payments); // ['1000/hr', '10000/day', '50000/week']
console.log(b); // {name: 'Batman', type: 'Hero', payments: Array(3)}
console.log(c); // {name: 'Ironman', type: 'Hero', payments: Array(3)}
const [ , , {name}] = employees;
console.log(name); // Ironman
Object의 Destructuring 에 대해서 좀 더 알아보도록 하자.
다음 코드를 보며 자세하게 알아보자.
let obj = {
// fileds, properties = key + value
name: 'Superman',
age: 27,
greet() {
console.log('hello');
},
};
// array 와 같은 경우는 순서가 상관이 있지만, object 같은 경우는 순서가 상관 없기 때문에
// let {name, greet} = obj; 해준다고 해도 각 이름에 맞게 값이 잘 설정된다.
let { name, age, greet } = obj;
// dot notation
console.log(name); // Superman
console.log(greet()); // hello
// 혹은 다음과 같이 이름을 다르게 쓸 수도 있다.
let { name, greet: myGreet } = obj;
console.log(myGreet()); // hello
위와 같은 방법은 각각의 value를 obj로부터 뽑아내는 형식이다.
Destructuring 과 예전에 공부했던 map helper method를 사용하면 훨씬 더 재밌는 예시도 만들 수 있다.
console.log([1, 2, 3, 4, 5, 6].map((x) => 2**x)); // [2, 4, 8, 16, 32, 64]
console.log([{ h:10, w:20, d:30 }].map(({h, w, d}) => h * w * d)); // [6000]
console.log([
{ h:10, w:20, d:30 },
{ h:11, w:21, d:31 },
{ h:12, w:22, d:32 },
{ h:13, w:23, d:33 },
{ h:14, w:24, d:34 },
{ h:15, w:25, d:35 },
{ h:16, w:26, d:36 },
].map(({h, w, d}) => h * w * d));
// [6000, 7161, 8448, 9867, 11424, 13125, 14976]
console.log([
{ h:10, w:20, d:30 },
{ h:11, w:21, d:31 },
{ h:12, w:22, d:32 },
{ h:13, w:23, d:33 },
{ h:14, w:24, d:34 },
{ h:15, w:25, d:35 },
{ h:16, w:26, d:36 },
].map((x) => x.h * x.w * x.d));
// [6000, 7161, 8448, 9867, 11424, 13125, 14976]
console.log([
{ h:10, w:20, d:30, f: 'whatever' },
{ h:11, w:21, d:31 },
{ h:12, w:22, d:32 },
{ h:13, w:23, d:33 },
{ h:14, w:24, d:34 },
{ h:15, w:25, d:35 },
{ h:16, w:26, d:36 },
].map((x) => x.h * x.w * x.d));
// [6000, 7161, 8448, 9867, 11424, 13125, 14976]
console.log([
{ h:10, w:20, d:30, f: 'whatever' },
{ h:11, w:21, d:31 },
{ h:12, w:22, d:32 },
{ h:13, w:23, d:33 },
{ h:14, w:24, d:34 },
{ h:15, w:25, d:35 },
{ h:16, w:26, d:36 },
].map((x) => x.h * x.w));
// [200, 231, 264, 299, 336, 375, 416]
console.log([
{ h:10, w:20, d:30, f: 'whatever' },
{ h:11, w:21, d:31 },
{ h:12, w:22, d:32 },
{ h:13, w:23, d:33 },
{ h:14, w:24, d:34 },
{ h:15, w:25, d:35 },
{ h:16, w:26, d:36 },
].map(({h, w}) => h * w));
// [200, 231, 264, 299, 336, 375, 416]
다음 코드를 구현사항에 맞게 바꾸어보도록하자.
// Refactor 'isEngineer' function to a single line
const superman = {
title: "Engineer",
department: "Engineering",
};
const batman = {
title: "Programmer",
department: "Coding",
};
function isEngineer(profile) {
let title = profile.title;
let department = profile.department;
return title === 'Engineer' && department === 'Engineering';
};
console.log(isEngineer(superman)); // true
console.log(isEngineer(batman)); // false
function isEngineer({ title, department }) {
return title === 'Engineer' && department === 'Engineering';
};
console.log(isEngineer(superman)); // true
console.log(isEngineer(batman)); // false
// const classesAsObject =
// [{ subject: 'Geography', time: '2PM', teacher: 'Ironman' }].
// Use map helper methods.
const classes = [
['Chemistry', '9AM', 'Superman'],
['Physics', '10:15AM', 'Batman'],
['Math', '11:30AM', 'Robin'],
];
const classesAsObject;
const classesAsObject = classes.map(([subject, time, teacher]) => {
return { subject, time, teacher };
});
console.log(classesAsObject); // [{…}, {…}, {…}]
// 0: {subject: 'Chemistry', time: '9AM', teacher: 'Superman'}
// 1: {subject: 'Physics', time: '10:15AM', teacher: 'Batman'}
// 2: {subject: 'Math', time: '11:30AM', teacher: 'Robin'}
// Output [2,4,6, ...]
const numbers = [1,2,3];
function double() {};
function double([number, ...rest]) {
return number ? [number * 2, ...double(rest)] : [];
};
// 혹은 다음과 같이 ...
const double = ([number, ...rest]) => number ? [number * 2, ...double(rest)] : [];
console.log(double(numbers)); // [2, 4, 6]