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

diffObjects

Returns the shallow difference between two objects. For each differing key, returns a tuple [aValue, bValue].

TypeScript
Copied!
1/**
2 * Returns the shallow difference between two objects.
3 * For each differing key, returns a tuple [aValue, bValue].
4 *
5 * @param a - First object.
6 * @param b - Second object.
7 * @returns An object of keys with different values between a and b.
8 */
9export function diffObjects(
10  a: Record<string, any>,
11  b: Record<string, any>
12): Record<string, [any, any]> {
13  const result: Record<string, [any, any]> = {};
14
15  const keys = new Set([...Object.keys(a), ...Object.keys(b)]);
16  for (const key of keys) {
17    if (a[key] !== b[key]) {
18      result[key] = [a[key], b[key]];
19    }
20  }
21
22  return result;
23}
  • Concise Shallow Comparison

    Identifies only the top-level differences between two objects, which is efficient for quick checks.

  • Symmetric Diff Output

    Returns both original and updated values as [aValue, bValue] tuples, offering full context for each change.

  • Combined Key Space

    Merges keys from both objects to ensure no additions or deletions are missed.

  • Minimal and Readable Logic

    Simple implementation using a Set and a single loop keeps performance high and code easy to maintain.

Tests | Examples

TypeScript
Copied!
1test('diffObjects - detects changed values', () => {
2  const a = { name: 'Alice', age: 30 };
3  const b = { name: 'Bob', age: 30 };
4  expect(diffObjects(a, b)).toEqual({ name: ['Alice', 'Bob'] });
5});
6
7test('diffObjects - detects added keys', () => {
8  const a = { a: 1 };
9  const b = { a: 1, b: 2 };
10  expect(diffObjects(a, b)).toEqual({ b: [undefined, 2] });
11});
12
13test('diffObjects - detects removed keys', () => {
14  const a = { a: 1, b: 2 };
15  const b = { a: 1 };
16  expect(diffObjects(a, b)).toEqual({ b: [2, undefined] });
17});
18
19test('diffObjects - empty objects', () => {
20  expect(diffObjects({}, {})).toEqual({});
21});
22
23test('diffObjects - same objects', () => {
24  const obj = { x: true, y: 42 };
25  expect(diffObjects(obj, { ...obj })).toEqual({});
26});
27
28test('diffObjects - shallow comparison only', () => {
29  const a = { config: { dark: true } };
30  const b = { config: { dark: true } };
31  expect(diffObjects(a, b)).toEqual({
32    config: [{ dark: true }, { dark: true }],
33  }); // different references
34});
35

Common Use Cases

  • Change Detection in State Management

    Identify changed keys between previous and current state snapshots.

  • Logging and Auditing

    Log differences in config, form submissions, or user actions for traceability.

  • Settings or Preferences Comparison

    Compare user-defined settings against defaults to determine overrides.

  • Debugging Tools and Inspectors

    Highlight modified fields in dev tools or internal UI diagnostics.

  • Patch Generation for Syncing

    Build shallow patches to send updates across the network or apply to external storage.

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