Skip to content

Latest commit

 

History

History
106 lines (73 loc) · 3.25 KB

File metadata and controls

106 lines (73 loc) · 3.25 KB

deep-diff-ts — Fast Deep Object Diff for TypeScript

npm version npm downloads license CI

Fast deep object diff and patch with full TypeScript types. Compare nested objects, arrays, dates, and regexps. Zero dependencies, ~1.4KB.

deep-diff-ts demo — comparing two objects and showing CREATE, UPDATE, DELETE changes

Install

npm install deep-diff-ts

Usage

import { diff } from "deep-diff-ts";

const oldObj = {
  name: "Alice",
  age: 30,
  tags: ["admin"],
  config: { theme: "dark" },
};

const newObj = {
  name: "Alice",
  age: 31,
  tags: ["admin", "editor"],
  config: { theme: "light" },
};

const changes = diff(oldObj, newObj);
// [
//   { type: "UPDATE", path: ["age"], oldValue: 30, value: 31 },
//   { type: "CREATE", path: ["tags", 1], value: "editor" },
//   { type: "UPDATE", path: ["config", "theme"], oldValue: "dark", value: "light" }
// ]

Apply Diffs

import { diff, applyDiff } from "deep-diff-ts";

const changes = diff(oldObj, newObj);
const result = applyDiff(oldObj, changes);
// result deeply equals newObj
// oldObj is not mutated

Diff Types

Each difference has a type and path:

Type Fields Description
CREATE path, value Property was added
UPDATE path, oldValue, value Property value changed
DELETE path, oldValue Property was removed

path is an array of keys/indices: ["users", 0, "name"]

Supported Types

  • Objects (deep recursive)
  • Arrays (element-by-element)
  • Dates (compared by time value)
  • RegExps (compared by string representation)
  • Primitives (string, number, boolean, null, undefined)
  • NaN (correctly handled via Object.is)

API

diff(oldObj, newObj)

Returns Difference[] describing all changes from oldObj to newObj.

applyDiff(target, diffs)

Returns a new object with all diffs applied. Does not mutate the original.

Other Projects

Author

Made by ofershap

LinkedIn GitHub


README built with README Builder

License

MIT