deep-diff, deep-object-diff, and object-diff are all npm packages designed to compute structural differences between JavaScript objects, including nested properties, arrays, and complex data types. These libraries help developers detect changes in state, synchronize data, or implement undo/redo functionality by identifying what has changed between two object snapshots. While they share a common goal, they differ significantly in API design, output format, handling of edge cases, and maintenance status.
When building frontend applications that track state changes — like form validation, real-time sync, or undo stacks — you often need to compare complex nested objects. Native equality checks (===) fail here because they only compare references. That’s where dedicated diffing libraries come in. Let’s examine how deep-diff, deep-object-diff, and object-diff approach this problem, and why one might be better suited for your use case.
First, a critical note: object-diff is deprecated. Its npm page states: "This package has been deprecated. Please use deep-object-diff instead." The GitHub repo is archived and read-only. It also has significant limitations:
{} even when differences exist in deeper levels// object-diff (deprecated — do not use)
import objectDiff from 'object-diff';
const a = { user: { name: 'Alice', age: 30 } };
const b = { user: { name: 'Alice', age: 31 } };
console.log(objectDiff(a, b)); // {} — fails to detect nested change!
Given these flaws and its unmaintained status, skip object-diff entirely. We’ll focus the rest of this comparison on the two viable options.
The biggest difference between deep-diff and deep-object-diff lies in what they return.
deep-diff gives you an array of change records, each describing the type of operation (N for new, D for deleted, E for edited, A for array), the path to the change, and old/new values.
// deep-diff
import diff from 'deep-diff';
const a = { user: { name: 'Alice', tags: ['dev'] } };
const b = { user: { name: 'Bob', tags: ['dev', 'frontend'] } };
const changes = diff(a, b);
console.log(changes);
// [
// { kind: 'E', path: ['user', 'name'], lhs: 'Alice', rhs: 'Bob' },
// { kind: 'A', path: ['user', 'tags'], index: 1, item: { kind: 'N', rhs: 'frontend' } }
// ]
This format is powerful when you need to interpret or replay changes — for example, to generate audit logs or apply patches later.
deep-object-diff, by contrast, returns a plain object showing only the paths and new values that differ. Deleted keys are represented with undefined.
// deep-object-diff
import diff from 'deep-object-diff';
const a = { user: { name: 'Alice', tags: ['dev'] } };
const b = { user: { name: 'Bob', tags: ['dev', 'frontend'] } };
const delta = diff(a, b);
console.log(delta);
// { user: { name: 'Bob', tags: ['dev', 'frontend'] } }
// For deletions:
const c = { name: 'Alice', role: 'admin' };
const d = { name: 'Alice' };
console.log(diff(c, d)); // { role: undefined }
This is simpler and integrates cleanly with patterns like Object.assign() or spread operators, making it great for lightweight state updates.
If you need to apply a diff back to an object (e.g., to revert a change), deep-diff includes a patch function:
// deep-diff: applying patches
import { diff, patch } from 'deep-diff';
const original = { count: 5 };
const updated = { count: 10 };
const changes = diff(original, updated);
const reverted = patch(updated, changes.map(change => ({
...change,
kind: change.kind === 'E' ? 'E' : change.kind, // invert logic as needed
// Note: full inversion requires custom logic per kind
})));
// deep-diff doesn't auto-invert, but provides tools to build patching
deep-object-diff has no built-in patching. You’d merge the delta manually:
// deep-object-diff: manual merge
import diff from 'deep-object-diff';
const base = { a: 1, b: 2 };
const delta = diff(base, { a: 3 });
const merged = { ...base, ...delta }; // { a: 3, b: 2 }
// But this fails for nested deletes — you'd need a recursive merge utility
So if patching or undo functionality is core to your app, deep-diff’s structured output gives you more control.
Both libraries handle nested objects and arrays, but differently.
Arrays:
deep-diff treats array modifications as special A (array) kind entries, showing index-level changes.deep-object-diff returns the entire new array if any element differs.// Array handling
const arrA = { items: [1, 2] };
const arrB = { items: [1, 3] };
// deep-diff
console.log(diff(arrA, arrB));
// [{ kind: 'A', path: ['items'], index: 1, item: { kind: 'E', lhs: 2, rhs: 3 } }]
// deep-object-diff
console.log(diff(arrA, arrB));
// { items: [1, 3] }
Dates and other objects:
deep-diff compares Date objects by value (via .getTime()), and handles RegExp, Buffer, etc.deep-object-diff compares non-plain objects by reference, so two new Date('2023') instances will appear different even if they represent the same time.Circular references:
deep-diff detects and safely skips circular structures.deep-object-diff may crash or recurse infinitely on circular objects (though recent versions attempt basic cycle detection).deep-object-diff follows a pure functional style: one function, one job, no side effects.
import diff from 'deep-object-diff';
const delta = diff(obj1, obj2);
deep-diff offers more methods (diff, patch, applyChange, revertChange) and optional configuration (like prefiltering properties), which adds flexibility at the cost of API surface area.
You want to avoid unnecessary re-renders by checking if state actually changed.
deep-object-diff{} (no change) or not. Simple and fast.const prev = store.getState();
const next = reducer(prev, action);
if (Object.keys(diff(prev, next)).length > 0) {
// dispatch update
}
You need to log exactly what changed in a user profile (e.g., “email changed from X to Y”).
deep-diffconst changes = diff(oldProfile, newProfile);
changes.forEach(change => {
if (change.kind === 'E') {
console.log(`${change.path.join('.')} changed from ${change.lhs} to ${change.rhs}`);
}
});
You send only changed fields to reduce payload size.
deep-object-diffconst local = { name: 'Alice', email: 'a@example.com' };
const server = { name: 'Alice', email: 'old@example.com' };
const patchBody = diff(server, local); // { email: 'a@example.com' }
fetch('/api/user', { method: 'PATCH', body: JSON.stringify(patchBody) });
| Feature | deep-diff | deep-object-diff | object-diff |
|---|---|---|---|
| Status | Unmaintained but functional | Actively maintained | ❌ Deprecated |
| Output | Array of change records | Plain delta object | Broken for nested objects |
| Patch Support | ✅ Built-in utilities | ❌ Manual merge only | ❌ |
| Array Diffing | ✅ Index-level changes | ❌ Full array replacement | ❌ |
| Non-Plain Objects | ✅ Handles Date, RegExp, etc. | ⚠️ Reference comparison only | ❌ |
| Circular References | ✅ Safe handling | ⚠️ May fail | ❌ |
| Use Case Fit | Audit logs, undo/redo, patching | Lightweight change detection | Do not use |
deep-diff, but test thoroughly in your environment.deep-object-diff is the modern, reliable choice.object-diff — it’s deprecated and fundamentally broken for real-world data.In most contemporary frontend applications, deep-object-diff strikes the best balance between simplicity, correctness, and maintainability. Reserve deep-diff for specialized scenarios where its rich metadata justifies the added complexity.
Choose deep-diff if you need a mature, feature-rich library that supports detailed change tracking (including kind of change like 'add', 'delete', 'edit', or 'array'), handles circular references, and provides utilities to apply patches. It’s well-suited for applications requiring precise diff interpretation and mutation replay, such as collaborative editing or state history systems. However, note that it hasn’t seen active development recently, so evaluate its compatibility with modern environments carefully.
Choose deep-object-diff if you prefer a minimal, functional approach that returns a plain object representing only the differing paths and values, without metadata about change types. It’s ideal for simple change detection where you just need to know ‘what’s different’ rather than ‘how it changed,’ and works well in Redux-style reducers or lightweight reactivity systems. Its zero-dependency, immutable design makes it easy to reason about and integrate.
Avoid object-diff in new projects — it is officially deprecated on npm and its GitHub repository is archived. The package lacks support for arrays, functions, dates, and other non-plain objects, and offers no meaningful advantages over maintained alternatives. Use deep-object-diff or deep-diff instead depending on your needs.
deep-diff is a javascript/node.js module providing utility functions for determining the structural differences between objects and includes some utilities for applying differences across objects.
npm install deep-diff
Possible v1.0.0 incompatabilities:
deep-diff does a pre-order traversal of the object graph, however, when it encounters an array, the array is processed from the end towards the front, with each element recursively processed in-order during further descent.npm install deep-diff
var diff = require('deep-diff')
// or:
// const diff = require('deep-diff');
// const { diff } = require('deep-diff');
// or:
// const DeepDiff = require('deep-diff');
// const { DeepDiff } = require('deep-diff');
// es6+:
// import diff from 'deep-diff';
// import { diff } from 'deep-diff';
// es6+:
// import DeepDiff from 'deep-diff';
// import { DeepDiff } from 'deep-diff';
<script src="https://cdn.jsdelivr.net/npm/deep-diff@1/dist/deep-diff.min.js"></script>
In a browser,
deep-diffdefines a global variableDeepDiff. If there is a conflict in the global namespace you can restore the conflicting definition and assigndeep-diffto another variable like this:var deep = DeepDiff.noConflict();.
In order to describe differences, change revolves around an origin object. For consistency, the origin object is always the operand on the left-hand-side of operations. The comparand, which may contain changes, is always on the right-hand-side of operations.
var diff = require('deep-diff').diff;
var lhs = {
name: 'my object',
description: 'it\'s an object!',
details: {
it: 'has',
an: 'array',
with: ['a', 'few', 'elements']
}
};
var rhs = {
name: 'updated object',
description: 'it\'s an object!',
details: {
it: 'has',
an: 'array',
with: ['a', 'few', 'more', 'elements', { than: 'before' }]
}
};
var differences = diff(lhs, rhs);
v 0.2.0 and above The code snippet above would result in the following structure describing the differences:
[ { kind: 'E',
path: [ 'name' ],
lhs: 'my object',
rhs: 'updated object' },
{ kind: 'E',
path: [ 'details', 'with', 2 ],
lhs: 'elements',
rhs: 'more' },
{ kind: 'A',
path: [ 'details', 'with' ],
index: 3,
item: { kind: 'N', rhs: 'elements' } },
{ kind: 'A',
path: [ 'details', 'with' ],
index: 4,
item: { kind: 'N', rhs: { than: 'before' } } } ]
Differences are reported as one or more change records. Change records have the following structure:
kind - indicates the kind of change; will be one of the following:
N - indicates a newly added property/elementD - indicates a property/element was deletedE - indicates a property/element was editedA - indicates a change occurred within an arraypath - the property path (from the left-hand-side root)lhs - the value on the left-hand-side of the comparison (undefined if kind === 'N')rhs - the value on the right-hand-side of the comparison (undefined if kind === 'D')index - when kind === 'A', indicates the array index where the change occurreditem - when kind === 'A', contains a nested change record indicating the change that occurred at the array indexChange records are generated for all structural differences between origin and comparand. The methods only consider an object's own properties and array elements; those inherited from an object's prototype chain are not considered.
Changes to arrays are recorded simplistically. We care most about the shape of the structure; therefore we don't take the time to determine if an object moved from one slot in the array to another. Instead, we only record the structural
differences. If the structural differences are applied from the comparand to the origin then the two objects will compare as "deep equal" using most isEqual implementations such as found in lodash or underscore.
When two objects differ, you can observe the differences as they are calculated and selectively apply those changes to the origin object (left-hand-side).
var observableDiff = require('deep-diff').observableDiff;
var applyChange = require('deep-diff').applyChange;
var lhs = {
name: 'my object',
description: 'it\'s an object!',
details: {
it: 'has',
an: 'array',
with: ['a', 'few', 'elements']
}
};
var rhs = {
name: 'updated object',
description: 'it\'s an object!',
details: {
it: 'has',
an: 'array',
with: ['a', 'few', 'more', 'elements', { than: 'before' }]
};
observableDiff(lhs, rhs, function (d) {
// Apply all changes except to the name property...
if (d.path[d.path.length - 1] !== 'name') {
applyChange(lhs, rhs, d);
}
});
A standard import of var diff = require('deep-diff') is assumed in all of the code examples. The import results in an object having the following public properties:
diff(lhs, rhs, prefilter, acc) — calculates the differences between two objects, optionally prefiltering elements for comparison, and optionally using the specified accumulator.observableDiff(lhs, rhs, observer, prefilter) — calculates the differences between two objects and reports each to an observer function, optionally, prefiltering elements for comparison.applyDiff(target, source, filter) — applies any structural differences from a source object to a target object, optionally filtering each difference.applyChange(target, source, change) — applies a single change record to a target object. NOTE: source is unused and may be removed.revertChange(target, source, change) reverts a single change record to a target object. NOTE: source is unused and may be removed.diffThe diff function calculates the difference between two objects.
lhs - the left-hand operand; the origin object.rhs - the right-hand operand; the object being compared structurally with the origin object.prefilter - an optional function that determines whether difference analysis should continue down the object graph.acc - an optional accumulator/array (requirement is that it have a push function). Each difference is pushed to the specified accumulator.Returns either an array of changes or, if there are no changes, undefined. This was originally chosen so the result would be pass a truthy test:
var changes = diff(obja, objb);
if (changes) {
// do something with the changes.
}
The prefilter's signature should be function(path, key) and it should return a truthy value for any path-key combination that should be filtered. If filtered, the difference analysis does no further analysis of on the identified object-property path.
const diff = require('deep-diff');
const assert = require('assert');
const data = {
issue: 126,
submittedBy: 'abuzarhamza',
title: 'readme.md need some additional example prefilter',
posts: [
{
date: '2018-04-16',
text: `additional example for prefilter for deep-diff would be great.
https://stackoverflow.com/questions/38364639/pre-filter-condition-deep-diff-node-js`
}
]
};
const clone = JSON.parse(JSON.stringify(data));
clone.title = 'README.MD needs additional example illustrating how to prefilter';
clone.disposition = 'completed';
const two = diff(data, clone);
const none = diff(data, clone,
(path, key) => path.length === 0 && ~['title', 'disposition'].indexOf(key)
);
assert.equal(two.length, 2, 'should reflect two differences');
assert.ok(typeof none === 'undefined', 'should reflect no differences');
When contributing, keep in mind that it is an objective of deep-diff to have no package dependencies. This may change in the future, but for now, no-dependencies.
Please run the unit tests before submitting your PR: npm test. Hopefully your PR includes additional unit tests to illustrate your change/modification!
When you run npm test, linting will be performed and any linting errors will fail the tests... this includes code formatting.
Thanks to all those who have contributed so far!