💻 오늘의 코드 팁 — Omit으로 객체에서 불필요한 필드 빼기
문제
API에서 받은 사용자 객체에 민감한 정보가 포함되어 있어서, 특정 필드만 제거하고 싶습니다.
```javascript
const user = {
id: 1,
name: "Alice",
email: "alice@example.com",
password: "hashed_password", // 이거 빼고 싶음
internalNotes: "...", // 이것도 빼고 싶음
};
// 수동으로 하면 복잡함
const safe = {
id: user.id,
name: user.name,
email: user.email,
};
```
새 필드가 추가될 때마다 수동으로 업데이트해야 한다는 게 번거롭습니다.
해결: Omit 함수
```javascript
// Omit 유틸리티 함수
function omit(obj, keys) {
const result = { ...obj };
keys.forEach(key => {
delete result[key];
});
return result;
}
// 사용
const user = {
id: 1,
name: "Alice",
email: "alice@example.com",
password: "hashed_password",
internalNotes: "...",
};
const safeUser = omit(user, ["password", "internalNotes"]);
console.log(safeUser);
// { id: 1, name: "Alice", email: "alice@example.com" }
```
TypeScript 버전 (타입 안전)
```typescript
function omit
obj: T,
keys: K[]
): Omit
const result = { ...obj };
keys.forEach(key => {
delete result[key];
});
return result as Omit
}
interface User {
id: number;
name: string;
email: string;
password: string;
internalNotes: string;
}
const user: User = { /* ... */ };
const safeUser = omit(user, ["password", "internalNotes"]);
// 타입: { id: number; name: string; email: string; }
```
설명
왜 쓸까?
Pick과의 차이:
라이브러리 사용:
```javascript
import { omit } from 'lodash-es';
const safeUser = omit(user, ['password', 'internalNotes']);
```
참고 링크
작지만 강력한 패턴입니다. 보안이 중요한 API 개발에서 매일 사용합니다!
👁 0 views
Comments (0)
💬
No comments yet.
Be the first to comment!