[TIL] 구조 분해 할당 (Destructuring)

JongYeon·2025년 1월 18일

TIL

목록 보기
19/69
post-thumbnail

구조 분해 할당

배열이나 객체의 속성을 해체하여 그 값을 개별 변수에 담는 ES6부터 사용 가능한 메서드다.

객체에서 구조 분해 할당

객체에서 구조 분해 할당에서는 key값이 중요허다!!!

예시1)

const person = {
    name: "김종연",
    age: 25,
    hometown: "경기도 광명",
};

const { name, age, hometown } = person; // 

console.log(name);
console.log(age);
console.log(hometown);

김종연
25
경기도 광명

예시2-1) 구조 분해 할당 전

function introduce(person) {
    console.log(
        `안녕하세요 ${person.name}입니다. 나이는 ${person.age}살 입니다.`
    );
}

const person = {
    name: "김종연",
    age: 25,
};
introduce(person);

안녕하세요 김종연입니다. 나이는 25살 입니다.

예시2-2)구조 분해 할당 후

//함수의 파라미터에도 적용 가능하다.
function introduce({ name, age }) {
    console.log(`안녕하세요 ${name}입니다. 나이는 ${age}살 입니다.`);
}

const person = {
    name: "김종연",
    age: 25,
};
introduce(person);

안녕하세요 김종연입니다. 나이는 25살 입니다.

예시3) 중첩 객체에서 구조 분해 할당

const movie = {
    title: "Inception",
    director: "Christopher Nolan",
    release: {
        year: 2025,
        month: "January",
    },
};

const {
    release: { year, month },
} = movie;

console.log(`현재는 ${year}${month}입니다.`);

현재는 2025년 January입니다.

문제

문제 풀기 전

function confirmReservation(user) {
    // 여기에 user 객체를 구조 분해 할당 하세요.

    return `${name} 고객님의 ${roomType}룸 입실날짜는 ${firstDate} 입니다.`;
}

const userInfo = {
    name: "James",
    roomType: "Deluxe",
    date: "2023-05-30",
};
const result = confirmReservation(userInfo);
console.log(result);

James 고객님의 Deluxe룸 입실날짜는 undefined 입니다.

문제 풀기 후

function confirmReservation(user) {
    // 여기에 user 객체를 구조 분해 할당 하세요.
 	const { name, roomType, date: firstDate } = user; // :(콜론)을 이용해 key값의 이름을 바꿀 수 있다.
  
    return `${name} 고객님의 ${roomType}룸 입실날짜는 ${firstDate} 입니다.`;
}

const userInfo = {
    name: "James",
    roomType: "Deluxe",
    date: "2023-05-30",
};
const result = confirmReservation(userInfo);
console.log(result);

James 고객님의 Deluxe룸 입실날짜는 2023-05-30 입니다.

배열에서 구조 분해 할당

배열에서 구조 분해 할당에서는 index값이 중요하다!!!

const person = ["김종연", 25, "서울시 금천구"];

const [, , thirdProfile] = person;

console.log(thirdProfile);

서울시 금천구

하루를 마치며

오늘은 React를 배우기 전 자바스크립트를 복습한 날이다. 뿐만아니라 평소 부족했던 html과 css를 보완하기 위해 구글 로그인 화면 클론코딩을 했다. 부모님 결혼기념을 맞이해서 같이 시간을 보낸 뒤 저녁8시 부터 공부하게됬다. 늦은 시간부터 공부하게됬지만 오랜만에 바람을 쐬서 기분이 좋았다. 주말에는 밖을 좀 나가야겠다.

profile
프론트엔드 공부중

0개의 댓글