AniUI Academy

Diff two objects into added, removed and updated

hardArrays & Objects+350 XPPractice

Sending the entire object on every save loses concurrent edits made by someone else and makes the audit log useless. Sending only what changed needs a diff.

Implement diffObjects(before, after). Compare only the top-level own keys of the two objects and return an object with exactly three keys: added, removed and updated, each a plain object, each empty when nothing falls into it. added maps each key present in after but not in before to its new value. removed maps each key present in before but not in after to its old value. updated maps each key present in both whose values differ to an object { from, to } holding the old and new values. Values are compared structurally to any depth: nested objects and arrays with the same contents count as unchanged, an array is never equal to a plain object, and NaN counts as equal to itself. A nested change is reported as one entry for the whole top-level key, with from and to being the whole old and new values. Neither input is modified.

Arguments

beforeObject
The previous state.
afterObject
The new state.

Returns

{ added: Object, removed: Object, updated: Object<string, { from, to }> } — Three buckets describing the top-level change. Unchanged keys are left out.

Examples

diffObjects({ a: 1, b: 2 }, { a: 1, b: 3, c: 4 });
// {
//   added:   { c: 4 },
//   removed: {},
//   updated: { b: { from: 2, to: 3 } },
// }
diffObjects({ a: { b: [1, 2] } }, { a: { b: [1, 2] } });
// { added: {}, removed: {}, updated: {} } — deep-equal values are unchanged

diffObjects({ a: { b: 1 } }, { a: { b: 2 } }).updated;
// { a: { from: { b: 1 }, to: { b: 2 } } } — nested changes report the whole value

What it has to do

  • Return exactly the keys added, removed and updated, each a plain object.
  • Compare only top-level own keys, but compare their values structurally to any depth.
  • Report each changed key as { from, to } under updated.
  • Leave unchanged keys out of the result entirely.
  • Treat NaN as equal to itself, and never treat an array as equal to a plain object.

Stuck? The javascript course covers everything this challenge needs.

Try it yourself
Loading playground...
5 tests · +350 XP

Discussion

Sign in to post
Sign in to join the conversation.Sign in

No comments yet. Be the first to say something.