filterObject
Filters object properties based on a predicate function.
1/**
2 * Filters object properties based on a predicate function.
3 *
4 * @param obj - The source object.
5 * @param fn - A predicate function that returns true to keep a key-value pair.
6 * @returns A new object with only the properties for which the predicate returns true.
7 */
8export function filterObject<T>(
9 obj: Record<string, T>,
10 fn: (val: T, key: string) => boolean
11): Record<string, T> {
12 return Object.keys(obj).reduce((acc, key) => {
13 if (fn(obj[key], key)) {
14 acc[key] = obj[key];
15 }
16 return acc;
17 }, {} as Record<string, T>);
18}
Flexible Predicate-Based Filtering
Enables precise control over which key-value pairs to retain using a customizable condition function.
Key-Aware and Value-Aware
Passes both key and value to the predicate, supporting complex filtering logic based on either or both.
Non-Mutating Design
Returns a new filtered object, leaving the original untouched and ensuring immutability.
Type-Safe and Reusable
Maintains type integrity through generics, making it safe to use across a wide range of object types.
Tests | Examples
1test('filterObject - filters values based on predicate', () => {
2 const input = { a: 1, b: 2, c: 3 };
3 const result = filterObject(input, val => val % 2 === 1);
4 expect(result).toEqual({ a: 1, c: 3 });
5});
6
7test('filterObject - predicate can use keys', () => {
8 const input = { foo: 1, bar: 2 };
9 const result = filterObject(input, (_, key) => key.startsWith('f'));
10 expect(result).toEqual({ foo: 1 });
11});
12
13test('filterObject - returns empty object when none match', () => {
14 const input = { a: 1, b: 2 };
15 const result = filterObject(input, () => false);
16 expect(result).toEqual({});
17});
18
19test('filterObject - works with empty input', () => {
20 expect(filterObject({}, () => true)).toEqual({});
21});
22
23test('filterObject - original object is not mutated', () => {
24 const input = { a: 1 };
25 const copy = { ...input };
26 filterObject(input, () => true);
27 expect(input).toEqual(copy);
28});
Common Use Cases
Form and Config Cleanup
Remove empty fields, defaults, or system-generated keys before submission or serialization.
Conditional Rendering or Logic
Build props or UI state dynamically by filtering only truthy or relevant values.
Permission-Based Field Exposure
Show or process only the fields a user is authorized to access.
Data Sanitization
Strip out undesired or invalid values from objects before saving or sending them.
Analytics and Metric Filtering
Include only active, non-zero, or relevant metrics from a report or tracking object.