compact
Creates a new object with all falsy values removed. Pass keep to preserve specific falsy values that should survive.
Try it
Section titled “Try it”Falsy values are false, 0, -0, 0n, "", null, undefined, and NaN. Matches in keep use Object.is, so 0 vs -0 and NaN are handled exactly.
Import
Section titled “Import”import { compact } from "1o1-utils";import { compact } from "1o1-utils/compact";Signature
Section titled “Signature”function compact<T extends Record<string, unknown>>({ obj, keep }: CompactParams<T>): Partial<T>Parameters
Section titled “Parameters”| Name | Type | Required | Description |
|---|---|---|---|
obj | T | Yes | The source object |
keep | unknown[] | No | Falsy values to preserve (matched via Object.is) |
Returns
Section titled “Returns”Partial<T> — A new object without falsy entries (except those listed in keep).
Examples
Section titled “Examples”compact({ obj: { a: 1, b: null, c: "", d: 0, e: false, f: "ok" } });// => { a: 1, f: "ok" }
// Preserve specific falsy valuescompact({ obj: { a: 0, b: null, c: "" }, keep: [0] });// => { a: 0 }
// Match NaN exactlycompact({ obj: { a: NaN, b: 1 }, keep: [NaN] });// => { a: NaN, b: 1 }Edge Cases
Section titled “Edge Cases”- Throws if
objis not an object. - Throws if
objis an array (use.filter(Boolean)instead). - Throws if
keepis provided but not an array. - Skips unsafe keys (
__proto__,constructor,prototype) to prevent prototype pollution. - Symbol-keyed properties are ignored (only string-keyed enumerable own properties are processed).
- Truthy values inside
keepare no-ops —keepis only useful for falsy values you want to preserve. - Distinguishes
0from-0viaObject.is. - Does not mutate the original object.
Also known as
Section titled “Also known as”remove falsy, clean object, drop empty, prune null
Prompt suggestion
Section titled “Prompt suggestion”I'm using 1o1-utils (npm: https://www.npmjs.com/package/1o1-utils, GitHub: https://github.com/pedrotroccoli/1o1-utils, LLM context: https://pedrotroccoli.github.io/1o1-utils/llms.txt). Show me how to use compact to strip null/undefined fields from an object before serializing.