[내배캠] 004. [JS] 객체와 배열 - 템플릿 리터럴, 구조 분해 할당
ES6 업데이트 이후 제공된 핵심 기능 세 가지에 대해 학습한다.
- Template Literals
- Destructuring
- Spread Operators
템플릿 리터럴 (Template Literals)
개념
변수와 표현식을 문자열 안에 삽입할 수 있게 해주는 문법.
사용법
`` 백틱을 이용한다.
const customer = {
name: '장원영',
};
const item = {
name: '커피',
price: 4000,
};
console.log( '감사합니다. ' + customer.name + '님!' + item.name + ' 을(를) ' + itme.price + '원에 구매하셨습니다.');
// '감사합니다. 장원영님! 커피을(를) 4000원에 구매하셨습니다.'
위와 같이 출력할 수도 있겠지만 너무 복잡하고 길어지기 때문에 템플릿 리터럴 문법을 사용하면 간편해진다.
const customer = {
name: '장원영',
};
const item = {
name: '커피',
price: 4000,
};
console.log(`감사합니다. ${customer.name}님! ${item.name}을(를) ${item.price}원에 구매하셨습니다.`);
// 템플릿 리터럴 안에서 변수의 값이나 함수를 호출할 때 ${} 달러 사인을 사용한다.
템플릿 리터럴은 줄바꿈도 인식하기 때문에 여러 줄을 넣을 때 \n
을 사용하지 않아도 된다.
const customer = {
name: '장원영',
};
const item = {
name: '커피',
price: 4000,
};
console.log(
`감사합니다.
${customer.name}님!
${item.name}을(를)
${item.price}원에
구매하셨습니다.`
);
// '감사합니다.
// 장원영님!
// 커피을(를)
// 4000원에
// 구매하셨습니다'
구조 분해 할당 (Destructuring)
개념
객체나 배열에서 속성이나 요소를 추출해서 개별 변수에 할당하는 작업을 말한다.
특히 React 프레임워크에서는 데이터를 객체 형태로 다루는 일이 많기 때문에 데이터를 간편하게 추출할 수 있다.
사용법
중요한 포인트는 객체나 배열에서 value를 추출해서 개별 변수에 할당하는 작업이라는 점이다.
- 객체나 배열에서 필요한 value를 고른다. 그리고 그 key를 찾는다.
- 따로 할당할 변수를 선언한다.
- 그 변수를 일반적인 선언 방식이 아닌 구조 분해 할당(Destructuring)을 한다.
객체에서의 구조 분해 할당
const person = {
name: '장원영',
age: 21
}
// 위 객체에서 name과 age를 변수에 할당할 수 있다.
const person = { name, age };
// 위와 같이 작성을 했다가
const { name, age } = person;
// 변수와 값의 자리를 바꾸면 구조 분해 할당이 된 것.
// 그러면 이제 아래와 같이 데이터 추출 가능.
console.log(name); // '장원영'
console.log(age); // 21
배열에서의 구조 분해 할당
객체에서는 순서에 상관없이 key를 찾아서 접근하지만, 배열은 순서가 중요하다.
let colors = ['red', 'blue', 'green'];
// 이 배열에서 첫 번째 인덱스의 색과 두 번째 인덱스의 색을 새로운 변수에 할당하고 싶다면?
let colors = [firstColor, secondColor];
// 이런 배열을 다시 거꾸로 바꾸어 구조 분해 할당한다.
let [firstColor, secondColor] = colors;
console.log(firstColor); // 'red'
console.log(secondColor); // 'blue'
firstColor
와 secondColor
는 위 배열의 값과 아무런 연관성이 없는 변수의 이름이다. 다만 인덱스 위치로 0번째, 1번째 인덱스로 인식한다.
따라서 다른 건 다 필요 없고 'green'라는 값만 필요하다고 한다면 아래와 같이 구조 분해 할당 할 수 있다.
let colors = ['red', 'blue', 'green'];
let [,,thirdColor] = colors;
console.log(thirdColor);
// 앞의 인덱스를 공백으로 두고 콤마로 구분해서 세 번째 인덱스 자리에 변수를 할당해주었다.
연습문제
- 주어진 객체에서
name
과age
를 구조 분해 할당을 사용해 추출하고 출력하시오.
문제
const person = {
name: '장원영',
age: 21,
job: '아이돌'
}
// 실행 기대값
// '장원영'
// '21'
나의 답
const person = {
name: '장원영',
age: 21,
job: '아이돌'
}
const {name, age} = person;
console.log(name); // '장원영'
console.log(age); // 21
- 주어진 객체에서
street
와city
를 구조 분해 할당을 사용해 추출하고 출력하시오.
문제
const employee = {
id: 101,
contact: {
phone: '123-456-7890',
address: {
street: '123 6th St',
city: 'Melbourne'
}
}
};
나의 답
const employee = {
id: 101,
contact: {
phone: '123-456-7890',
address: {
street: '123 6th St',
city: 'Melbourne'
}
}
};
const { employee.contact.address.street, employee.contact.address.city } = employee;
console.log( street, city ); // 에러
모범 답안
const employee = {
id: 101,
contact: {
phone: '123-456-7890',
address: {
street: '123 6th St',
city: 'Melbourne'
}
}
};
const { contact: { address: { street, city } } } = employee;
console.log(street); // '123 6th St'
console.log(city); // 'Melbourne'
설명
const employee = {
id: 101,
contact: {
phone: '123-456-7890',
address: {
street: '123 6th St',
city: 'Melbourne'
}
}
};
// 이 변수는 객체 안에 객체가, 또 그 객체 안에 객체가 중첩된 객체이다.
// employee 객체 안에 contact 객체 안에 address 객체 안에 street와 city라는 속성이 존재.
// 순서대로 뜯어 보면 아래와 같다.
const { contact } = employee;
console.log(contact);
// {
// "phone": "123-456-7890",
// "address": {
// "street": "123 6th St",
// "city": "Melbourne"
// }
//}
const { contact: { address } } = employee;
console.log(address);
//{
// "street": "123 6th St",
// "city": "Melbourne"
//}
const { contact: { address: { street, city } } } = employee;
console.log(street); // '123 6th St'
console.log(city); // 'Melbourne'
// 한 개의 객체에서 특정 키를 구조 분해 할당할 땐 const { contact } = employee 와 같이 사용했지만
// 객체 안에 있는 또 다른 객체로 들어갈 땐
// const { contact: { address } } 와 같이 : 콜론으로 이어 들어 간다.
- 주어진 배열에서 첫 번째와 세 번째 요소를 구조 분해 할당을 사용해 추출하고 출력하세요.
문제
const colors = ['red', 'blue', 'green', 'yellow'];
나의 답
const colors = ['red', 'blue', 'green', 'yellow'];
const [firstColor,,thirdColor] = colors;
console.log(firstColor); // 'red'
console.log(thirdColor); // 'green'
- 주어진 배열에서 첫 번째 요소를 제외한 나머지를 구조 분해 할당을 사용해 새 배열로 만들고 출력하시오.
문제
const numbers = [10, 20, 30, 40, 50];
나의 답
// 수정 전
const numbers = [10, 20, 30, 40, 50];
const [ , 1, 2, 3, 4] = numbers;
const newNumberArr = [1, 2, 3, 4];
console.log(newNumberArr);
// 수정 후
const numbers = [10, 20, 30, 40, 50];
const [ , a, b, c, d] = numbers;
const newNumberArr = [a, b, c, d];
console.log(newNumberArr); // [20, 30, 40, 50]
// 수정 사유 : 구조 분해 할당에서 분해를 할 때 사용 되는 assignment는 '변수'의 이름이다.
// 변수명은 숫자로 시작할 수 없으며
// 문자나 $, _로 시작해야만 한다.
언제 쓰나?
- React에서 컴포넌트에 props를 전달하고 이를 다룰 때, 구조 분해 할당하면 가독성이 크게 향상됨.
- API 응답 데이터 다룰 때.
fetch('https://api.example.com/user')
.then(response => response.json())
.then(({ id, name, address }) => {
console.log(`User ID: ${id}, Name: ${name}, Address: ${address.city}`);
});
- 함수의 매개변수로 객체나 배열을 전달할 때
const user = {
id: 'wonyoung123',
name: '장원영',
age: 21
}
const { id, name, age } = user;
function myFunction( { id, name, age } ) {
console.log(`Processing User ID: ${id}, name: ${name}`);
}
myFunction(user);
// "Processing User ID: wonyoung123, name: 장원영"
'Programing > React' 카테고리의 다른 글
001. [코딩애플] [part1] React란? (0) | 2024.05.14 |
---|---|
React-Create-App 환경과 Vite 환경에서 각각 실행하는 법 (0) | 2024.05.13 |
[내배캠] 003. [JS] 객체와 배열 - (0) | 2024.05.10 |
[내배캠] 002. [JS] 객체와 배열 - 값 접근하기, 수정하기, 삭제하기 (0) | 2024.05.10 |
[내배캠] 001. [JS] 변수 (let, const, var) 와 스코프, 호이스팅 (0) | 2024.05.10 |
댓글