JavaScript
[JavaScript] 객체 비구조화(구조 분해)
spring92
2021. 8. 16. 17:54
person이라는 객체가 있다.
const person = {
firstName: "John",
lastName: "Watson",
};
이 객체의 firstName과 lastName을 콘솔에 출력하려면 이렇게 하면 된다.
const person = {
firstName: "John",
lastName: "Watson",
};
const firstName = person.firstName;
const lastName = person.lastName;
console.log(firstName, lastName); // John Watson
하지만 이 방식은 person.을 반복하고 있기 때문에 비효율적이다. 비구조화 할당을 사용하면 반복을 피하고 코드의 양을 줄일 수 있다.
const person = {
firstName: "John",
lastName: "Watson",
};
const { firstName, lastName } = person; // 비구조화
console.log(firstName, lastName); // John Watson
비구조화 할당 코드의 의미를 풀어보자면,
객체 person의 내부에 들어가서
firstName의 값 "John"을 변수 firstName에 할당하고,
lastName의 값 "Watson"을 변수 lastName에 할당하라는 뜻이다.
값을 할당할 변수의 이름을 바꿀 수도 있다.
const person = {
firstName: "John",
lastName: "Watson",
};
const { firstName: first, lastName: last } = person; // 할당할 변수의 이름 바꾸기
console.log(first, last); // John Watson
객체 person의 내부에 들어가서
fisrtName의 값 "John"을 변수 first에 할당하고,
lastName의 값 "Watson"을 변수 last에 할당하라는 뜻이다.
객체 내부의 객체에 접근해서 값을 가져올 때도 사용가능하다.
const person = {
firstName: "John",
lastName: "Watson"
friend: {
male: "Sherlock"
},
};
const { friend: { male } } = person;
console.log(male); // Sherlock
friend: male이면 객체 person의 내부에서 friend의 값을 찾아 변수 male에 할당한다는 의미이지만,
friend: { male }이면 객체 person의 내부 객체 friend의 내부로 들어가 male의 값을 변수 male에 할당한다는 의미이다.
마찬가지로 값을 할당할 변수의 이름을 변경할 수 있다.
const { friend: { male: maleFriend } } = person;
console.log(maleFriend); // Sherlock