Skip to content

compact

Removes all entries with falsy values (false, null, undefined, 0, "", NaN) from an object. Own keys that are prototype-polluting strings (__proto__, constructor, prototype) are silently skipped.

Available since v2.0.0

import { compact } from '@helpers4/object';
// or, from the all-in-one package (same code, one install):
import { compact } from 'helpers4/object';
compact<T extends Record<string, unknown>>(obj: T): Partial<T>
ParameterTypeDescription
objTThe source object

Partial<T> — A new object containing only entries with truthy values

Removes all entries with falsy values (false, null, undefined, 0, "", NaN).

compact({ a: 1, b: null, c: '', d: 0, e: 'hello' })
// => { a: 1, e: 'hello' }

Useful to strip empty or missing fields before sending data.

compact({ name: 'Alice', email: '', age: 0, role: 'admin' })
// => { name: 'Alice', role: 'admin' }

View source on GitHub