@philiprehberger/pick-omit
v0.2.0
Published
Type-safe shallow and deep pick/omit utilities for JavaScript objects
Readme
@philiprehberger/pick-omit
Type-safe shallow and deep pick/omit utilities for JavaScript objects
Installation
npm install @philiprehberger/pick-omitUsage
import { pick, omit } from '@philiprehberger/pick-omit';
pick({ a: 1, b: 2, c: 3 }, 'a', 'c'); // { a: 1, c: 3 }
omit({ a: 1, b: 2, c: 3 }, 'b'); // { a: 1, c: 3 }Deep pick/omit
import { deepPick, deepOmit } from '@philiprehberger/pick-omit';
const user = { name: 'Alice', address: { city: 'NYC', zip: '10001' } };
deepPick(user, 'name', 'address.city'); // { name: 'Alice', address: { city: 'NYC' } }
deepOmit(user, 'address.zip'); // { name: 'Alice', address: { city: 'NYC' } }Predicate-based filters
import { pickBy, omitBy } from '@philiprehberger/pick-omit';
pickBy({ a: 1, b: null, c: 'ok' }, (v) => v != null); // { a: 1, c: 'ok' }
omitBy({ a: 1, b: null, c: 'ok' }, (v) => v == null); // { a: 1, c: 'ok' }Pick by typeof
import { pickByType } from '@philiprehberger/pick-omit';
const obj = { name: 'Alice', age: 30, active: true };
pickByType(obj, 'string'); // { name: 'Alice' }
pickByType(obj, 'number'); // { age: 30 }
pickByType(obj, 'boolean'); // { active: true }Flatten and unflatten
import { flatten, unflatten } from '@philiprehberger/pick-omit';
const nested = { user: { name: 'Alice', tags: ['admin', 'staff'] } };
const flat = flatten(nested);
// { 'user.name': 'Alice', 'user.tags.0': 'admin', 'user.tags.1': 'staff' }
unflatten(flat);
// { user: { name: 'Alice', tags: ['admin', 'staff'] } }
flatten({ a: { b: 1 } }, '/'); // { 'a/b': 1 }API
| Method | Description |
|--------|-------------|
| pick(obj, ...keys) | Returns a new object with only the specified keys |
| omit(obj, ...keys) | Returns a new object without the specified keys |
| deepPick(obj, ...paths) | Picks nested values using dot-notation paths |
| deepOmit(obj, ...paths) | Removes nested values using dot-notation paths |
| pickBy(obj, predicate) | Picks entries where the predicate returns true |
| omitBy(obj, predicate) | Omits entries where the predicate returns true |
| pickByType(obj, typeName) | Keeps properties whose typeof matches typeName |
| flatten(obj, separator?) | Converts a nested object/array into a flat dot-notation map |
| unflatten(obj, separator?) | Inverse of flatten; numeric segments become array indices |
Development
npm install
npm run build
npm testSupport
If you find this project useful:
