const getPerson = () => {
return {
firstName:"John",
lastName:"Doe",
age:20,
<email:"[email protected]>",
city:"owlCity",
country:"USA",
nomadCoders:{
html:true,
css:true,
javascript:false
},
};
};
다음과 같은 object에 접근하고 싶습니다. 본래의 방식은 아래와 같습니다.
const person = getPerson();
console.log(person.firstName); //"John"
console.log(person.nomadCoders.html); //true
반면 object destructing을 사용하면 object 안의 key를 더 쉽게 받아올 수 있습니다.
const { firstName, lastName } = getPerson();
console.log(firstName); //"John"
console.log(lastName); //"Doe"
아래와 같이 2중, 3중으로 접근하는 것도 가능합니다.
const {nomadCoders:{html}} = getPerson();
console.log(html); //true
const getList = () => {
return ["어떤", "것을", "리스트에", "써볼까요"]
}
다음과 같은 list에 접근하고 싶습니다. 원래의 방식은 아래와 같습니다.
const MyArray = getList();
console.log(MyArray[0]); //"어떤"
console.log(MyArray[1]); //"것을"
반면 list destructing을 이용하면 배열의 요소를 한번에 가져올 수 있습니다.
const [ 변수1, 변수2, 변수3, 변수4 ] = getList();
console.log(변수1); //"어떤"
console.log(변수2); //"것을"
변수1,변수2,변수3,변수4의 이름은 임의로 정하시면 됩니다.