구조분해할당 : 선언한 객체, 배열 안에서 일주 변수, 요소만 빼서 저장하는 기능.(선언이 간편해진다.)


본래 age라는 객체 안의 변수만 출력하고자 하면 에러가 발생한다.
그래서 객체.변수명 을 써서 출력하는 것.

하지만 비구조화 할당은 또다른 변수에 객체 안에서 뽑아온 본래 변수를 담아주는 것이라 할 수 있다.
{변수1} = {변수1 : 값 , 변수2 : 값}
[배열 요소3] = [배열요소1, 배열요소2, 배열요소3]
(getChild() 는 return 값을 괄호로 가져온것이니 참고.)

배열은 객체처럼 줄을 띄우면 에러발생.

* 객체는 키값이 중요하고, 배열은 순서가 중요하다.
배열은 아래처럼 다음 값만 원한다 하더라도 앞에 오는 요소부터 고려해야함.

구조분해 할당 응용 코드
최종적으로 이 형태를 쓴다. 각 변수에는 객체의 값들이 저장되어 있어서
함수로 넘어가더라도 각 변수 그대로 이어진다.
// shorthand property names 적용
const result = getWelcomeTemplate({ name, age, school, createdAt });
myUser 객체가 해당 프로퍼티들을 가지고 있다면, 그 프로퍼티 값들이 함수 내부의 지역 변수(name, age, school, createdAt)로 자동으로 할당됩니다.
즉, 함수 선언 시 구조 분해 할당의 형태로 매개변수를 정의해두면, 함수를 호출할 때 해당 구조에 맞는 객체를 전달하면 자동으로 프로퍼티 값을 해당 변수에 할당하는 방식으로 동작합니다.
// 02-03-welcome-template-destructuring-1 / index.js
// 구조분해할당으로 변경
function getWelcomeTemplate({ name, age, school, createdAt }){
return `
<html>
<body>
<h1>${name}님 가입을 환영합니다.</h1>
<hr />
<div>이름: ${name}</div>
<div>나이: ${age}살</div>
<div>학교: ${school}</div>
<div>가입일: ${createdAt}</div>
</body>
</html>
`
}
const myUser = {
name: '철수',
age: 13,
school: '다람쥐초등학교',
createdAt: '2010-09-07',
}
const result = getWelcomeTemplate(myUser);
console.log(result);
{name, age, school, createdAt}와 myUser 간의 관계를 더 명확히 설명드리겠습니다.
함수 내에서 {name, age, school, createdAt} = myUser의 형식으로 표현되지는 않습니다. 대신 함수를 호출할 때 myUser 객체를 전달하면, 함수 내부에서는 해당 객체의 프로퍼티들을 바로 변수로 사용할 수 있게 됩니다. 이것이 바로 구조 분해 할당의 특징입니다.
즉, 함수 내부에서는 name, age, school, createdAt이라는 변수들을 직접 사용하게 됩니다. 이 변수들은 함수를 호출할 때 전달된 myUser 객체의 프로퍼티 값들을 참조합니다. 이 기능은 호이스팅과는 별개의 특성입니다.
myUser 객체가 해당 프로퍼티들을 가지고 있다면, 그 프로퍼티 값들이 함수 내부의 지역 변수(name, age, school, createdAt)로 자동으로 할당됩니다.
즉, 함수 선언 시 구조 분해 할당의 형태로 매개변수를 정의해두면, 함수를 호출할 때 해당 구조에 맞는 객체를 전달하면 자동으로 프로퍼티 값을 해당 변수에 할당하는 방식으로 동작합니다.
매개변수와 아래의 shorthand property names가 1대1로 각각 연결되어 서로의 갯수가 달라도 사용이 가능해진다.
키 값의 선언 없이 변수명 만으로도 객체할당이 가능해진다.


// shorthand property names 적용
const result = getWelcomeTemplate({ name, age, school, createdAt });
프로터티의 key와 프로퍼티의 value가 같으면 value는 생략할 수 있다.

function getWelcomeTemplate({ name, age, school, createdAt }) {
....
}
const name = '철수'
const age = 13
const school = '다람쥐초등학교'
const createdAt = '2010-09-07'
// const myUser = {
// name,
// age,
// school,
// createdAt,
// };
// shorthand property names 적용
const result = getWelcomeTemplate({ name, age, school, createdAt });
console.log(result);
문제
부분함수를 올바르게 완성하라.
<부분함수 내용>
부분마다 돌려보려 하니까 이렇게 나오더라?
함수호출을 객체로만 해도 부분함수들이 알아서 객체에서 부분적으로 필요한 것만 할당을 알아서 하네?
신기할 따름이다.
function checkValidationEmail({ email }) {
if (email === undefined) {
console.log("이메일 주소가 없어요")
return false
} else if ([...email].includes("@") === false) {
console.log("@부호가 빠졌어요")
return false
} else {
return true
}
}
function getWelcomeTemplate({ school, age, name }) {
return `
<html>
<body>
<h1>${name}님 가입을 환영합니다.</h1>
<hr />
<div>이름: ${name}</div>
<div>나이: ${age}살</div>
<div>학교: ${school}</div>
</body>
</html>
`
}
function sendWelcomeTemplateToEmail({ email }, template) {
console.log(`${email}님을 환영합니다. !!!!!!!!!!!!!!!!${template}`)
}
const myUser = {
name: '철수',
age: 13,
school: '다람쥐초등학교',
email: 'a@a.com',
};
const result = checkValidationEmail(myUser)
console.log(result)
const result2 = getWelcomeTemplate(myUser)
console.log(result2)
const result3 = sendWelcomeTemplateToEmail(myUser, getWelcomeTemplate(myUser))
console.log(result3)
객체 변수를 매개변수로 호출하면 구조분해 할당을 쓰면된다.
export function checkValidationEmail({ email }) {
if (email === undefined) {
console.log("이메일 주소가 없어요")
return false
} else if ([...email].includes("@") === false) {
console.log("@부호가 빠졌어요")
return false
} else {
return true
}
}
const myUser = {
name: '철수',
age: 13,
school: '다람쥐초등학교',
email: 'a@a.com',
};
const result = checkValidationEmail(myUser)
console.log(result)

하지만 다음처럼 객체.키 값을 써서 함수를 호출할 경우
아래처럼 객체의 키값이 있는데 구조분해할당을 매개변수로 쓰면 undefined가 출력된다.
export function checkValidationEmail({ email }) {
if (email === undefined) {
console.log("이메일 주소가 없어요")
return false
} else if ([...email].includes("@") === false) {
console.log("@부호가 빠졌어요")
return false
} else {
return true
}
}
const myUser = {
name: '철수',
age: 13,
school: '다람쥐초등학교',
email: 'a@a.com',
};
const result = checkValidationEmail(myUser.email)
console.log(result)

그렇다! 객체.키 값은 매개변수 값 자체로 들어가는 것이다.
export function checkValidationEmail(a) {
if (a === undefined) {
console.log("이메일 주소가 없어요")
return false
} else if ([...a].includes("@") === false) {
console.log("@부호가 빠졌어요")
return false
} else {
return true
}
}
const myUser = {
name: '철수',
age: 13,
school: '다람쥐초등학교',
email: 'a@a.com',
};
const result = checkValidationEmail(myUser.email)
console.log(result)
이제 이 다음은 저 윗과 아래를 연결해주는 것.(위의 내용 중에서 출력부분만 날리고 export만 쓰면 된다.)

보충내용
원시 데이터 타입 (예: 숫자, 문자열, 불린)의 경우, 비구조화 할당을 사용하면 값이 복사됩니다
const obj = { number: 100, text: "Hello" };
const { number, text } = obj;
console.log(number); // 100
console.log(text); // "Hello"
그러나 객체나 배열과 같은 참조 데이터 타입의 경우, 비구조화 할당을 통해 변수에 할당되는 것은 원본의 참조입니다
const obj = { innerObj: { key: "value" } };
const { innerObj } = obj;
innerObj.key = "changed";
console.log(obj.innerObj.key); // "changed"
'🪢node > node 이론 정리' 카테고리의 다른 글
스프레드연산자 || 얕은/깊은복사 || REST 파라미터 (0) | 2023.10.08 |
---|---|
Date 객체 사용해보기 + .toString().padStart(자릿수, 문자) (0) | 2023.10.06 |
파사드 패턴과 import 하기 (0) | 2023.10.05 |
우분투에 vscode 연동 (0) | 2023.10.04 |
터미널 통해 wsl 우분투 설치 및 버전 확인 + node.js 설치 (0) | 2023.10.03 |