Diff Two Flat Objects

Compare two flat objects field by field and report added, removed, and changed keys, the core of audit logging and change detection.

JavascriptData Integrity

Code

javascriptsnippet
16 lines
export function diffObjects(before, after) {
  const changes = [];
  const keys = new Set([...Object.keys(before), ...Object.keys(after)]);
  for (const key of keys) {
    const had = Object.prototype.hasOwnProperty.call(before, key);
    const has = Object.prototype.hasOwnProperty.call(after, key);
    if (!had && has) {
      changes.push({ key, type: "added", value: after[key] });
    } else if (had && !has) {
      changes.push({ key, type: "removed", value: before[key] });
    } else if (before[key] !== after[key]) {
      changes.push({ key, type: "changed", from: before[key], to: after[key] });
    }
  }
  return changes;
}

How it works

One way to read it: the function diffObjects, doing all the work.

Repetition is confined to for (const key of keys) — the rest of the file is straight-line.

Putting it to use

The entry-point signature is export function diffObjects(before, after)

diffObjects is the public entry point; everything else in the file exists to support it.

Core lines

const keys = new Set([...Object.keys(before), ...Object.keys(after)]);

Interactive Tools for This Topic

FAQ

Is the dependency story complicated?
Not at all: zero dependencies, so there is nothing to version or audit. The file defines `diffObjects` at load time.