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.
Code
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
Date Difference CalculatorCalculate the number of days, weeks, whole months, and years between two ISO dates, computed in UTC.Diff Ignoring WhitespaceCompare two blocks of text line by line and separate true differences from lines that differ only in spacing, indentation, or line endings.JSON Diff ViewerCompare two JSON documents and list every added, removed, and changed path in a structural diff, with clear before and after values.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.