일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 | 29 |
30 | 31 |
- UNiQUE
- googleapis
- AWS
- 부자아빠가난한아빠2
- 일상속귀한배움
- 개발자
- 세이노의가르침
- 오브젝트
- 스터디
- 조영호
- validator
- nodemailer
- typescript
- 역행자
- 객체지향의사실과오해
- serverless
- 클린코드
- Nestjs
- 자청
- 북스터디
- BOOK
- Object
- 독후감
- OOP
- PRISMA
- futureself
- nodejs
- Study
- 퓨처셀프
- Validation
- Today
- Total
우당탕탕 우리네 개발생활
[JS] 객체 내 property를 동적으로 만들 수 있다? 본문
여느 때와 같이 개발을 하던 중 다음과 같은 상황에 직면했습니다.
const input: {
catId: number | null;
dogId: number | null;
fishId: number | null;
counts: number;
name: string;
} = /**/
const data: {
catCounts?: number;
catName?: string;
dogCounts?: number;
dogName?: string;
fishCounts?: number;
fishName?: string;
} = {};
if (input.catId) {
data.catCounts = counts;
data.catName = name;
} else if (input.dogId) {
data.dogCounts = counts;
data.dogName = name;
} else if (input.fishId) {
data.fishCounts = counts;
data.fishName = name;
}
cat, dog, fish 중 존재하는 종의 name과 counts를 data에 채운 후 추후에 update구문에 사용하는 것이 미션이었습니다.
직관적으로 코드를 작성한 후 잠시 고민에 빠졌습니다.
cat, dog, fish만 동적으로 적용할 수 있다면 코드가 간결해질 수 있겠는데..
시간이 그리 많지 않은 상황이었기에 아쉬운 상황으로 코드리뷰를 진행하게 되었습니다.
하지만 이게 웬 떡인지 훌륭한 동료와의 코드 리뷰를 통해 해답을 찾게 되었습니다.
우선 그 적용의 결과는 아래와 같습니다.
const input: {
catId: number | null;
dogId: number | null;
fishId: number | null;
counts: number;
name: string;
} = /**/
const kindPrefix = input.catId
? 'cat'
: data.dogId
? 'dog'
: data.fishId
? 'fish'
: '';
const data: {
catCounts?: number;
catName?: string;
dogCounts?: number;
dogName?: string;
fishCounts?: number;
fishName?: string;
} = {
[`${kindPrefix}Counts`]: counts;
[`${kindPrefix}Name`]: name;
};
먼저번 예제에서 data 객체를 빈 객체로 만들어 놓은 것과 if 조건문을 통해 중복된 counts와 name을 반복하며 사용한 것을 개선했으면 좋겠다는 작은 아쉬움이 있었는데, 이 두 가지 문제를 한꺼번에 해결할 수 있었습니다.
위와 같이 square brackets([]) 안에 string, number, symbol, any값을 대입하여 동적으로 생성할 수 있는 property를 computed property라고 부른다고 하며 ES6문법에서부터 지원한다고 합니다. 아래와 같이 직접 typescript playground에서도 확인해 볼 수 있었습니다.
또한 아래와 같이 method name에도 위 문법을 사용할 수 있는 경우도 확인할 수 있었습니다.
let name = 'fullName';
class Person {
constructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
get [name]() {
return `${this.firstName} ${this.lastName}`;
}
}
let person = new Person('John', 'Doe');
console.log(person.fullName);
마치며
제가 유용하게 위 문법을 사용했던 것처럼 이 글을 참고하시는 분들도 유용하게 적용하실 수 있었으면 좋겠습니다.
출처
https://www.javascripttutorial.net/es6/javascript-computed-property/
JavaScript Computed Properties
In this tutorial, you'll learn about the JavaScript computed properties and how to use them effectively.
www.javascripttutorial.net
'tech' 카테고리의 다른 글
[Nestjs] nodemailer로 메모리상의 엑셀파일을 전송해봤습니다 (0) | 2024.04.04 |
---|---|
[Nestjs] 결국 @nest-modules/mailer 대신 nodemailer를 사용했습니다 (0) | 2024.03.30 |
[Prisma] update와 updateMany의 where option은 다르다 (0) | 2024.03.09 |
[Nestjs] 간단한 이슈를 해결하려다 @Cron과 node-cron 오픈소스를 뜯어보게 되었습니다? (1) | 2024.02.26 |
[Slack] Console에서 Incoming Webhook 생성해보기 (1) | 2024.02.24 |