object-pick-omit-ts
v1.0.0
Published
Ultra-fast, type-safe nested object projection with dot-notation path support for picking and omitting properties in TypeScript.
Maintainers
Readme
object-pick-omit-ts
Ultra-fast, type-safe nested object projection with dot-notation path support for picking and omitting properties in TypeScript.
Why object-pick-omit-ts?
Transforming objects is one of the most common tasks in JavaScript and TypeScript. However:
- Lodash Overhead: Importing
lodash.pickorlodash.omitpulls in multiple transitive dependencies and bloated prototype chains. - Missing Dot Notation: Standard solutions only handle flat top-level keys. Extracting deeply nested fields (e.g.
user.profile.avatar) requires writing fragile traversal code. - Security Vulnerabilities: Naive object property pickers are susceptible to prototype pollution exploits via
__proto__andconstructorattacks. - TypeScript Safety: You lose autocompletion and strict compile-time types when relying on un-typed helper libraries.
object-pick-omit-ts provides an elegant, robust solution:
- Strictly Typed:
pickandomitpreserve native TypeScript type inference (Pick<T, K>andOmit<T, K>). - Dot-Notation Path Projections: Use
pickDeepandomitDeepwith dot paths like'profile.settings.theme'effortlessly. - Prototype-Pollution Protected: Hardened against
__proto__,constructor, andprototypeinjection vectors. - Conditional Projections:
pickByandomitByfilter by value or predicate. - Zero Dependencies: Pure TypeScript, tiny footprint (<750 bytes minified & gzipped).
Installation
Install using your preferred package manager:
# npm
npm install object-pick-omit-ts
# pnpm
pnpm add object-pick-omit-ts
# yarn
yarn add object-pick-omit-ts
# bun
bun add object-pick-omit-tsQuick Start
import { pick, omit, pickDeep, omitDeep } from 'object-pick-omit-ts';
interface User {
id: number;
name: string;
email: string;
passwordHash: string;
role: string;
}
const user: User = {
id: 42,
name: 'Alex',
email: '[email protected]',
passwordHash: 'argon2_secret_hash',
role: 'member',
};
// 1. Type-safe Pick
const publicProfile = pick(user, ['id', 'name']);
// Result type: Pick<User, 'id' | 'name'>
console.log(publicProfile); // { id: 42, name: 'Alex' }
// 2. Type-safe Omit
const safeRecord = omit(user, ['passwordHash']);
// Result type: Omit<User, 'passwordHash'>
console.log(safeRecord); // { id: 42, name: 'Alex', email: '[email protected]', role: 'member' }Real-World Examples
Example 1: Sanitizing Database Records for Public API Responses
Prevent accidental data leaks (passwords, internal salts, access tokens) before sending responses over the wire:
import { omit } from 'object-pick-omit-ts';
export async function getUserEndpoint(req, res) {
const dbUser = await db.users.findById(req.params.id);
// Strip sensitive internal fields safely
const publicUser = omit(dbUser, [
'passwordHash',
'twoFactorSecret',
'resetToken',
'internalNotes',
]);
return res.json(publicUser);
}Example 2: Deep Nested Dot-Notation Extraction (pickDeep)
Extract only necessary nested fields from complex nested third-party payloads (like Stripe, GitHub, or Shopify webhooks):
import { pickDeep } from 'object-pick-omit-ts';
const stripeWebhookEvent = {
id: 'evt_12345',
type: 'customer.subscription.created',
data: {
object: {
id: 'sub_999',
customer: 'cus_555',
plan: {
id: 'plan_pro',
amount: 2900,
currency: 'usd',
},
status: 'active',
},
},
};
// Project only essential properties
const summary = pickDeep(stripeWebhookEvent, [
'id',
'type',
'data.object.customer',
'data.object.plan.amount',
]);
console.log(summary);
/*
{
id: 'evt_12345',
type: 'customer.subscription.created',
data: {
object: {
customer: 'cus_555',
plan: {
amount: 2900
}
}
}
}
*/Example 3: Deep Nested Omit (omitDeep)
Remove confidential sub-properties from complex nested configurations without mutating the source:
import { omitDeep } from 'object-pick-omit-ts';
const serverConfig = {
app: { name: 'Storefront', port: 3000 },
database: {
host: 'localhost',
port: 5432,
credentials: {
username: 'db_admin',
password: 'super_secret_password',
},
},
};
const safeConfig = omitDeep(serverConfig, [
'database.credentials.password',
]);
console.log(safeConfig.database.credentials);
// { username: 'db_admin' }Example 4: Conditional Filtering with pickBy and omitBy
Strip empty, null, or undefined values before saving to database:
import { omitBy } from 'object-pick-omit-ts';
const formData = {
title: 'New Post',
description: '',
published: true,
coAuthor: null,
tags: undefined,
};
// Remove null and undefined values
const cleaned = omitBy(formData, (val) => val === null || val === undefined);
console.log(cleaned);
// { title: 'New Post', description: '', published: true }API Reference
pick<T, K>(obj, keys)
Creates an object composed of the selected keys.
obj: Source object.keys: Array of keys ((keyof T)[]).- Returns:
Pick<T, K>.
omit<T, K>(obj, keys)
Creates an object omitting the selected keys.
obj: Source object.keys: Array of keys ((keyof T)[]).- Returns:
Omit<T, K>.
pickBy<T>(obj, predicate)
Filters object entries where predicate(value, key) returns true.
predicate:(value: T[keyof T], key: keyof T) => boolean.- Returns:
Partial<T>.
omitBy<T>(obj, predicate)
Filters object entries where predicate(value, key) returns false.
predicate:(value: T[keyof T], key: keyof T) => boolean.- Returns:
Partial<T>.
pickDeep<T>(obj, paths)
Projects nested dot-notation paths (e.g. ['user.profile.avatar']) into a newly constructed nested object.
omitDeep<T>(obj, paths)
Deeply clones an object and deletes the specified dot-notation paths without mutating the original input.
Contributing
Contributions, issues, and feature requests are welcome! Feel free to check the issues page.
License
MIT © Pirapaakaran Pirathapan
Support & Sponsor
If you find this utility useful in your projects, please consider supporting my open-source work:
