🛠️ 처음부터 만드는 Pick — 객체에서 필요한 키만 추출하기
Pick이 뭔가요?
API 응답에서 불필요한 필드를 제거하거나, 폼 제출할 때 특정 필드만 보낼 때가 있습니다. Pick은 객체에서 원하는 키들만 골라 새 객체를 만드는 함수입니다.
```javascript
const user = {
id: 1,
name: 'Alice',
email: 'alice@example.com',
password: 'secret123',
createdAt: '2025-01-01'
};
// password와 createdAt은 빼고 싶어요
const publicUser = pick(user, ['id', 'name', 'email']);
// { id: 1, name: 'Alice', email: 'alice@example.com' }
```
기본 구현
```javascript
function pick(obj, keys) {
return keys.reduce((result, key) => {
if (key in obj) {
result[key] = obj[key];
}
return result;
}, {});
}
```
간단하죠? `reduce`로 각 키를 순회하면서, 원본 객체에 있는 키만 새 객체에 추가합니다.
실제 예제: API 응답 정제
```javascript
// 백엔드에서 받은 전체 사용자 정보
const apiResponse = {
userId: 42,
userName: 'bob_smith',
email: 'bob@example.com',
hashedPassword: 'bcrypt$...',
internalNotes: 'VIP customer',
lastLoginIP: '192.168.1.1'
};
// 프론트에 보낼 것만
const safeData = pick(apiResponse, ['userId', 'userName', 'email']);
```
TypeScript 버전
```typescript
function pick
obj: T,
keys: K[]
): Pick
return keys.reduce((result, key) => {
if (key in obj) {
result[key] = obj[key];
}
return result;
}, {} as Pick
}
type User = { id: number; name: string; email: string; password: string };
const user: User = { id: 1, name: 'Alice', email: 'alice@example.com', password: 'secret' };
const safe = pick(user, ['id', 'name', 'email']); // 타입 안전!
```
내부 키만 추출 (filter 조합)
```javascript
// 객체에 있는 모든 키 중 특정 접두사만
function pickByPrefix(obj, prefix) {
const keys = Object.keys(obj).filter(k => k.startsWith(prefix));
return pick(obj, keys);
}
const config = { apiKey: '...', apiSecret: '...', dbUrl: '...' };
pickByPrefix(config, 'api'); // { apiKey: '...', apiSecret: '...' }
```
공식 문서: [Lodash `pick`](https://lodash.com/docs/#pick) | [TypeScript Utility Types](https://www.typescriptlang.org/docs/handbook/utility-types.html#picktype-keys)
👁 0 views
Comments (0)
💬
No comments yet.
Be the first to comment!