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

cleanObjectBy

Removes object entries based on a custom predicate function.

TypeScript
Copied!
1/**
2 * Removes or replaces properties in an object based on a predicate function.
3 *
4 * @param obj - The object to clean.
5 * @param predicate - Function that returns 'true' for values to remove or replace.
6 * @param fallback - Optional value to insert instead of removing the property.
7 * @returns A new cleaned object.
8 */
9export function cleanObjectBy<T extends Record<string, any>>(
10  obj: T,
11  predicate: (val: any, key: string) => boolean,
12  fallback?: any
13): Partial<T> {
14  const result: Partial<T> = {};
15
16  for (const [key, value] of Object.entries(obj)) {
17    if (predicate(value, key)) {
18      if (fallback !== undefined) {
19        result[key as keyof T] = fallback;
20      }
21    } else {
22      result[key as keyof T] = value;
23    }
24  }
25
26  return result;
27}
  • Predicate-Based Flexibility

    Enables custom logic for filtering or replacing properties based on keys, values, or both.

  • Optional Fallback Support

    Allows you to replace unwanted values instead of removing them, making the utility dual-purpose.

  • Type-Safe and Partial Output

    Uses Partial<T> to accurately reflect the fact that some properties may be removed or replaced.

  • Non-Destructive and Pure

    Returns a new object without mutating the input, ensuring safe use in functional data flows.

  • Readable and Explicit Logic

    Clear use of Object.entries() with straightforward conditions improves maintainability.

Tests | Examples

TypeScript
Copied!
1test('cleanObjectBy - removes values matching predicate', () => {
2  const obj = { a: 1, b: null, c: '', d: undefined, e: 5 };
3  const result = cleanObjectBy(obj, val => val == null || val === '');
4  expect(result).toEqual({ a: 1, e: 5 });
5});
6
7test('cleanObjectBy - replaces removed values with fallback', () => {
8  const obj = { a: 1, b: null, c: '', d: undefined, e: 5 };
9  const result = cleanObjectBy(obj, val => val == null || val === '', 'fallback');
10  expect(result).toEqual({ a: 1, b: 'fallback', c: 'fallback', d: 'fallback', e: 5 });
11});
12
13test('cleanObjectBy - supports custom logic', () => {
14  const obj = { a: 1, b: 0, c: -1, d: 10 };
15  const result = cleanObjectBy(obj, val => val < 1);
16  expect(result).toEqual({ a: 1, d: 10 });
17});
18
19test('cleanObjectBy - fallback with number', () => {
20  const obj = { a: 1, b: null, c: 2 };
21  const result = cleanObjectBy(obj, val => val == null, 0);
22  expect(result).toEqual({ a: 1, b: 0, c: 2 });
23});

Common Use Cases

  • Advanced Form Cleanup

    Remove or default empty, invalid, or temporary form fields before submission.

  • Conditional Payload Filtering

    Customize request bodies based on runtime conditions or user roles.

  • Dynamic Configuration Normalization

    Replace or strip out dev-only flags, placeholders, or disabled features before production use.

  • Content Sanitization

    Clean out untrusted or user-generated values (e.g., filter profanity or dangerous input).

  • Custom Debug Logging

    Redact or replace sensitive fields (like tokens or passwords) before logging structured data.

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