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

snippet
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;
}