Skip to content

Diffing

Get structured change records from two object snapshots.

Previous: Tutorial · Next: Patching

Playground

Open Diff explorer → — edit before/after JSON and inspect change records live.

Problem → approach

Without structured diffWith diff()
String compare or shallow === misses nested editsDeep walk with path-addressable change records
Building a change list by hand for every form/storeresult.changes with type, path, before, after
Full diff cost when you only need a dirty flaghasChanges() short-circuits without materializing changes

Basics

ts
import { diff } from "@jayoncode/object-diff";

const result = diff({ user: { name: "John" }, count: 1 }, { user: { name: "Jane" }, count: 2 });

console.log(result.changes);
console.log(result.metadata.changeCount);

Dirty check only

Skip building the full change list when you only need a boolean:

ts
import { hasChanges } from "@jayoncode/object-diff";

if (!hasChanges(savedState, currentState)) {
  return; // nothing to persist
}

Filtered helpers

Extract subsets of changes:

ts
import { added, removed, updated, unchanged } from "@jayoncode/object-diff";

const result = diff(before, after);
const newKeys = added(result);
const deleted = removed(result);
const modified = updated(result);

Compare and options

ts
import { compare } from "@jayoncode/object-diff";

const equal = compare(objA, objB); // deep equality check

Useful diff() options include maxDepth, includeUnchanged, and custom comparators — see API Reference.

Cheat sheet

ts
const result = diff(before, after);
result.changes; // readonly change records
result.metadata; // counts, timing hints
hasChanges(before, after); // fast path

Next: Patching — turn changes into JSON Patch operations.

JOC is a JayOnCode monorepo of @jayoncode/* packages. Docs sync from source via TypeDoc and sync scripts.