Yevhen Klymentiev
dark
light
console
darkness
y.klymentiev@gmail.com
Reusable Snippets|Practical utility code for everyday use — custom-built and ready to share

cleanObject

Removes null, undefined, and empty string values from an object.

TypeScript
Copied!
1/**
2 * Removes null, undefined, and empty string values from an object.
3 *
4 * @param obj - The input object.
5 * @returns A new object with empty values removed.
6 */
7export function cleanObject(obj: Record<string, any>): Record<string, any> {
8  return Object.fromEntries(
9    Object.entries(obj).filter(([_, v]) => v !== null && v !== undefined && v !== '')
10  );
11}
  • Effective Noise Reduction

    Removes null, undefined, and empty strings — common "empty" values that clutter or corrupt data.

  • Concise and Readable

    Implements cleanup logic with a modern, declarative pattern using Object.entries and filter.

  • Non-Mutating and Safe

    Produces a new object without modifying the original input, preserving immutability.

  • Flexible for Generic Objects

    Works on any plain object regardless of value types, making it broadly applicable.

Tests | Examples

TypeScript
Copied!
1test('cleanObject - removes null, undefined, and empty strings', () => {
2  const input = { a: 'value', b: null, c: undefined, d: '', e: 0, f: false };
3  expect(cleanObject(input)).toEqual({ a: 'value', e: 0, f: false });
4});
5
6test('cleanObject - returns empty object when all values are empty', () => {
7  const input = { a: null, b: undefined, c: '' };
8  expect(cleanObject(input)).toEqual({});
9});
10
11test('cleanObject - keeps falsy but valid values', () => {
12  const input = { zero: 0, bool: false, emptyStr: '', undef: undefined };
13  expect(cleanObject(input)).toEqual({ zero: 0, bool: false });
14});
15
16test('cleanObject - works with already clean object', () => {
17  const input = { name: 'Alice', age: 25 };
18  expect(cleanObject(input)).toEqual(input);
19});
20
21test('cleanObject - does not affect nested objects', () => {
22  const input = { a: '', nested: { b: null } };
23  expect(cleanObject(input)).toEqual({ nested: { b: null } });
24});

Common Use Cases

  • Form Data Sanitization

    Remove unfilled or optional fields before submission to APIs or validation logic.

  • Payload Optimization

    Clean up request bodies to avoid sending unnecessary or meaningless data.

  • Configuration Cleanup

    Eliminate falsy or placeholder config entries before use or storage.

  • Logging and Debugging

    Output only meaningful key-value pairs for better visibility and focus.

  • Filtering Dynamic Object State

    Prepare clean state slices when updating or syncing user input in reactive applications.

Codebase: Utilities -> Objects -> cleanObject | Yevhen Klymentiev