Skip to content
SDETRole
SDETRole

Diff two flat objects

intermediate JSON Challenge 6 of 18

Write diffObjects(before, after) for two flat objects, such as an expected and an actual API response. It returns { added, removed, changed }.

Requirements

  • added: keys that exist only in after, with their values.
  • removed: keys that exist only in before, with their values.
  • changed: keys in both whose values differ, as { from, to }.
  • Decide presence by whether the key exists, not by whether the value is undefined.
  • Compare values with Object.is semantics, so 1 and '1' differ and NaN equals NaN.
  • Do not mutate either input.

Expected output

diffObjects({ a: 1, b: 2 }, { b: 3, c: 4 }) → { added: { c: 4 }, removed: { a: 1 }, changed: { b: { from: 2, to: 3 } } }

Test cases (6)

  • ○reports added, removed and changed keys
  • ○identical objects produce an empty diff
  • ○a key present with value undefined is not missing
  • ○type changes count as changes
  • ○NaN compared with NaN is unchanged
  • ○does not mutate the inputs
solution.jsExecutes in your browser

Ctrl/⌘ + Enter to run tests · your code is saved in this browser

Results

Run the tests to see results here.

Type to search across SDETRole.

Full-text search by Pagefind · runs in your browser Open search page →