구조 분해 할당
ES6의 구조 분해 할당(Destructuring)은 배열이나 객체의 속성을 해체해 그 값을 개별 변수에 담을 수 있게 하는 Javascript 표현식이다.
객체 구조 분해 할당
클린 코드를 위해 사용한다.
function buildAnimal (animalData) {...}
function buildAnimal(animalData) {
let accessory = animalData.accessory,
animal = animalData.animal,
color = animalData.color,
hairType = animalData.hairType;
}
let obj = {
accessory: "horn",
animal: "horse",
color: "purple",
hairType: "curly",
};
function buildAnimal(animalData) {}
let { accessory, animal, color, hairType } = animalData;
깊이 들어간 객체 구조 분해 할당
let person = {
name: "Maya",
age: 30,
phone: "123",
address: {
zipcode: 1234,
street: "rainbow",
number: 42,
},
};
let {
address: { zipcode, street, number },
} = person;
console.log(zipcode, street, number); // 1234 rainbow 42
배열 구조 분해 할당
let a, b, rest;
[a, b] = [10, 20];
console.log(a);
// expected output: 10
console.log(b);
// expected output: 20
[a, b, ...rest] = [10, 20, 30, 40, 50];
console.log(rest);
// expected output: Array [30,40,50]
const week = ["monday", "tuesday", "wednesday", "thuresday", "friday"];
const day1 = week[0];
const day2 = week[1];
const day3 = week[2];
const day4 = week[3];
const day5 = week[4];
const week = ["monday", "tuesday", "wednesday", "thuresday", "friday"];
const [day1, day2, day3, day4, day5] = week;
const numbers = [1, 2, 3, 4, 5, 6];
const [, , three, , five] = numbers;
const studentDetails = {
firstName: "John",
lastName: "Mary",
};
const { firstName: fName = "not given", lastName } = studentDetails;
console.log(fName);
console.log(lastName);
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"