JavaScript의 구조 분해 할당(Destructuring Assignment)은 객체나 배열의 속성 값을 간결한 문법으로 추출해 개별 변수에 담을 수 있게 해주는 기능입니다. ES 모듈(ES Module)로 가져온(import) 객체도 일반 객체와 완전히 동일한 방식으로 구조 분해할 수 있습니다.
가져온 객체 구조 분해 예제
다음은 import로 가져온 객체를 구조 분해하는 전체 예제 코드입니다.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.result {
font-size: 18px;
font-weight: 500;
color: rebeccapurple;
}
</style>
</head>
<body>
<h1>JavaScript에서 가져온 객체 구조 분해하기</h1>
<div class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>위 버튼을 클릭하면 person 객체가 구조 분해됩니다</h3>
<script src="script.js" type="module"></script>
</body>
</html>
script.js
import person from "./sample.js";
let resEle = document.querySelector(".result");
let BtnEle = document.querySelector(".Btn");
let {firstName, lastName, age} = person;
BtnEle.addEventListener("click", () => {
resEle.innerHTML = 'firstName = '+firstName+'<br>';
resEle.innerHTML += 'lastName = '+lastName+'<br>';
resEle.innerHTML += 'age = '+age+'<br>';
});
sample.js
export default {
firstName:'Rohan',
lastName:'Sharma',
age:22,
}
코드 설명
- 모듈 가져오기:
import person from "./sample.js"는 sample.js 파일의 기본 내보내기(default export) 객체를 person 변수로 불러옵니다. - 구조 분해:
let {firstName, lastName, age} = person;단 한 줄만으로 객체의 세 속성이 각각 같은 이름의 변수에 자동으로 할당됩니다. - 결과 출력: 버튼 클릭 이벤트가 발생하면 구조 분해된 변수 값들이
.result영역에 순서대로 표시됩니다.
출력 결과
위 코드를 실행하면 다음과 같은 화면이 나타납니다.

'CLICK HERE' 버튼을 클릭하면 구조 분해된 값이 아래와 같이 화면에 표시됩니다.
