객체 스트럭처링 할당
객체
와 배열
은 자바스크립트에서 가장 많이 사용된다.
함수에 객체나 배열을 전달해야 하는 경우가 많은데 객체나 배열에 저장된 데이터 전체가 아닌 일부만 필요할 경우가 생긴다.
이럴 때 객체나 배열을 변수로 분해
할 수 있게 해주는 특별한 문법이 있다.
그것이 객체 스트럭처링 할당(destucturing assignment)
이다.
// 이름과 성을 요소로 가진 배열
let arr = ['Bora', 'Lee'];
/*
객체 스트럭처링 할당을 이용해
firstName에는 arr[0]을
surName에는 arr[1]을 할당한다.
*/
let [firstName, surName] = arr;
console.log(firstName);
console.log(surName);
위 처럼 객체 스트럭처링 할당을 하게되면 배열에 접근하지 않고 변수명으로 접근이 가능해진다.
배열의 요소를 직접 변수에 할당하는 것보다 코드의 양이 줄어든다는 점만 다르다.
// let [firstName, surName] = arr;
let firstName = arr[0];
let surName = arr[1];
두 변수에 저장된 값을 교환할 때 객체 스트럭처링 할당을 사용할 수 있다.
let guest = 'Jane';
let admin = 'Pete';
// 변수 guest에는 Pete, 변수 admin에는 Jane이 저장되도록 값을 교환
[guest, admin] = [admin, guest];
console.log(`${guest} ${admin}`); // Pate Jane
//기본값
let [name = 'Guest', surName = 'Anonymous'] = ['Julius'];
console.log(name); //Julius
console.log(surName); //Anonymous
let options = {
title: 'Menu',
width: 100,
height: 200
};
let {title, width, height} = options;
console.log(title); //Menu
console.log(width); //100
console.log(height); //200
프로퍼티 options.title
과 options.width
, options.height
에 저장된 값이 상응하는 변수에 할당된 것을 확인할 수 있다.
순서는 중요하지않고 변수명과 키값이 같으면 같은 변수명에 할당된다.
객체의 프로퍼티 키와 다른 변수 이름으로 프로퍼티 값을 할당받으려면 다음과 같이 변수를 선언한다.
const user = { firstName: 'Unmgo', lastName: 'Lee' };
// 프로퍼티 키를 기준으로 디스트럭처링 할당이 이루어진다.
// 프로퍼티 키가 lastName인 프로퍼티 값을 ln에 할당하고,
// 프로퍼티 키가 firstName인 프로퍼티 값을 fn에 할당한다.
const { lastName: ln, firstName: fn } = user;
console.log(fn, ln); // Unmgo Lee
객체 디스터럭처링 할당을 위한 변순에 기본값을 설정할 수 있다.
const { firstName = 'Ungmo', lastName } = { lastName: 'Lee' };
console.log(firstName, lastName); //Ungmo Lee
const { firstName: fn = 'Ungmo', lastName: ln } = { lastName: 'Lee' };
console.log(fn, ln); //Ungmo Lee
객체 스트럭처링 할당은 객체를 인수로 전달받는 함수의 매개변수에도 사용할 수 있다.
function printTodo({ content, completed}) {
console.log(`할일 ${content}은 ${completed ? '완료' : '비완료'} 상태입니다.`);
}
printTodo({id: 1, content: 'Html', completed: true}); // 할일 Html은 완료 상태입니다.
중첩 객체일 경우는 다음과 같이 사용한다.
const user = {
name: 'Lee',
address: {
zipCode: '03068',
city: 'Seoul'
}
};
// address 프로퍼티 키로 객체를 추출하고 이 객체의 city 프로퍼티 키로 값을 추출한다.
const { address: { city } } = user;
console.log(city); // Seoul
객체 디스트럭처링 할당을 할때 Rest 프로퍼티 ...
을 사용할 수 있다.
// Rest 프로퍼티
const {x, ...rest} = {x: 1, y: 2, z: 3};
console.log(x, rest); //1 {y: 2, z: 3}
객체를 공부하다보니 모르는 것도 많고
Java에서 없었던 구문들이 생소하지만 편하고 배우면서 즐거웠다.
아직 객체만해도 갈 길이 멀지만 차근차근 단단히 쌓아올려야겠다.
급하지만 급하지 않게(?) 나아가보자!