JavaScriptFundamental (ES6), part 1
Diff two objects in JavaScript
124 diff two objects, then apply the diff
hardCompare two versions of a record and report { added, removed, changed }, where changed holds [before, after] pairs. Compare values deeply, so a nested object with identical contents counts as unchanged even though it is a different object. Then write apply and show that the diff really does turn the old record into the new one.
Stuck? Three hints, smallest first
- 1. The keys to consider are the union of both key lists:
[...new Set([...Object.keys(a), ...Object.keys(b)])]. - 2. Use
Object.hasOwn, not a truthy check, or a field explicitly set toundefinedlooks like a missing one. - 3. Deep equality is four lines of recursion: identical, then reject non-objects, then compare key counts, then
every.
const deepEqual = (a, b) => {
if (a === b) return true;
if (typeof a !== 'object' || typeof b !== 'object' || a === null || b === null) return false;
const ak = Object.keys(a);
const bk = Object.keys(b);
return ak.length === bk.length && ak.every((k) => deepEqual(a[k], b[k]));
};
const diff = (before, after) => {
const keys = [...new Set([...Object.keys(before), ...Object.keys(after)])];
return keys.reduce((acc, key) => {
const had = Object.hasOwn(before, key);
const has = Object.hasOwn(after, key);
if (!had) return { ...acc, added: { ...acc.added, [key]: after[key] } };
if (!has) return { ...acc, removed: { ...acc.removed, [key]: before[key] } };
if (deepEqual(before[key], after[key])) return acc;
return { ...acc, changed: { ...acc.changed, [key]: [before[key], after[key]] } };
}, { added: {}, removed: {}, changed: {} });
};
const apply = (base, d) => {
const next = { ...base, ...d.added };
for (const key of Object.keys(d.removed)) delete next[key];
for (const [key, [, to]] of Object.entries(d.changed)) next[key] = to;
return next;
};
const before = { name: 'Mama Nkechi', lga: 'Ikeja', phone: '08031234567', stall: { row: 'B', number: 12 }, tags: ['veg'] };
const after = { name: 'Mama Nkechi', lga: 'Surulere', stall: { row: 'B', number: 12 }, tags: ['veg', 'fruit'], since: 2019 };
const d = diff(before, after);
const nothing = diff(before, before);
const blanked = diff({ a: 1 }, { a: undefined });
const nanDiff = diff({ takings: NaN }, { takings: NaN });
console.log('changed:', d.changed);
console.log('added :', d.added, '| removed:', d.removed);
console.log('applied:', apply(before, d));
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('only the fields that really differ are reported', Object.keys(d.changed), ['lga', 'tags']);
test('with both sides, so the report is enough for an audit line', d.changed.lga, ['Ikeja', 'Surulere']);
test('a key only one side has is added or removed, not changed', [d.added, d.removed], [{ since: 2019 }, { phone: '08031234567' }]);
test('two different objects with the same contents count as unchanged', [before.stall === after.stall, Object.hasOwn(d.changed, 'stall')], [false, false]);
test('a record against itself produces an empty diff', [Object.keys(nothing.added).length, Object.keys(nothing.changed).length, Object.keys(nothing.removed).length], [0, 0, 0]);
test('setting a field to undefined is a change, not a removal', [Object.keys(blanked.changed), Object.keys(blanked.removed)], [['a'], []]);
test('NaN never equals itself, so a NaN field looks changed every time', [Object.keys(nanDiff.changed), nanDiff.changed.takings.every(Number.isNaN)], [['takings'], true]);
test('applying the diff to the old record reconstructs the new one', deepEqual(apply(before, d), after), true);
test('and this equality ignores key order, where a stringify comparison does not', [deepEqual({ a: 1, b: 2 }, { b: 2, a: 1 }), same({ a: 1, b: 2 }, { b: 2, a: 1 })], [true, false]);
A diff is the honest way to log a change. "Vendor updated" tells nobody anything; lga: Ikeja → Surulere is an audit trail, an undo, and a patch to send over the wire. Keeping both sides in changed is what makes all three possible from one structure.
Deep comparison is the part people get wrong by reaching for JSON.stringify(a) === JSON.stringify(b). The last assertion shows why: stringify is sensitive to key order, so two objects carrying identical information compare as different, and your diff reports a change that did not happen. It also drops undefined, turns a Date into a string and throws on a cycle. Four lines of recursion avoid all of that.
Two edges are worth remembering. Object.hasOwn rather than a truthy or undefined check is what separates "the field is gone" from "the field is present and empty", which are different events in a form. And NaN !== NaN, so any numeric field that can be NaN will appear in every diff for ever unless the leaf comparison uses Object.is.