deep-diff, jsondiffpatch, and object-diff are utilities designed to identify changes between two JavaScript objects or JSON structures. They are essential for tasks like state management debugging, syncing data across clients, or optimizing re-renders by detecting specific mutations. While they share a common goal, they differ significantly in output format, array handling, and support for applying patches back to objects.
When managing state in complex frontend applications, knowing exactly what changed between two data snapshots is crucial. deep-diff, jsondiffpatch, and object-diff all solve this problem, but they approach it from different angles. One focuses on detailed change logs, another on compact data patches, and the third on simplicity. Let's break down how they handle real-world engineering tasks.
The way each library represents a difference defines how you will process it later.
deep-diff returns an array of change objects.
// deep-diff
import { diff } from 'deep-diff';
const lhs = { name: 'Alice' };
const rhs = { name: 'Bob' };
const changes = diff(lhs, rhs);
// Output: [ { kind: 'E', path: [ 'name' ], lhs: 'Alice', rhs: 'Bob' } ]
jsondiffpatch returns a delta object that mirrors the original structure.
[ old, new ].// jsondiffpatch
import * as jsondiffpatch from 'jsondiffpatch';
const lhs = { name: 'Alice' };
const rhs = { name: 'Bob' };
const delta = jsondiffpatch.diff(lhs, rhs);
// Output: { name: [ 'Alice', 'Bob' ] }
object-diff returns a single object with three keys.
added, removed, changed.// object-diff
import diff from 'object-diff';
const lhs = { name: 'Alice' };
const rhs = { name: 'Bob' };
const result = diff(lhs, rhs);
// Output: { changed: { name: { from: 'Alice', to: 'Bob' } } }
In many scenarios, you don't just want to see the diff — you want to apply it to another object or undo it.
deep-diff provides an applyDiff function.
// deep-diff
import { applyDiff } from 'deep-diff';
const target = { name: 'Alice' };
const changes = [ { kind: 'E', path: [ 'name' ], rhs: 'Bob' } ];
applyDiff(target, changes);
// target is now { name: 'Bob' }
jsondiffpatch excels here with patch and reverse.
// jsondiffpatch
import * as jsondiffpatch from 'jsondiffpatch';
const target = { name: 'Alice' };
const delta = { name: [ 'Alice', 'Bob' ] };
jsondiffpatch.patch(target, delta);
// target is now { name: 'Bob' }
const reverseDelta = jsondiffpatch.reverse(delta);
object-diff does not include a built-in patcher.
// object-diff
// No built-in apply function
// You must manually iterate over result.changed to update your object
const result = diff(lhs, rhs);
// Manual logic required to apply result.changed to a target
Arrays are the hardest part of diffing. Did an item move, or was it deleted and a new one added?
deep-diff tracks array changes by index.
// deep-diff
const lhs = { list: [ 1, 2 ] };
const rhs = { list: [ 1, 3 ] };
const changes = diff(lhs, rhs);
// Output shows index 1 changed from 2 to 3
// [ { kind: 'E', path: [ 'list', 1 ], lhs: 2, rhs: 3 } ]
jsondiffpatch uses array mapping by default.
// jsondiffpatch
const lhs = { list: [ 1, 2 ] };
const rhs = { list: [ 1, 3 ] };
const delta = jsondiffpatch.diff(lhs, rhs);
// Output represents the change within the array structure
// { list: { '1': [ 2, 3 ] } } (simplified representation)
object-diff treats arrays as primitive values or simple lists.
// object-diff
const lhs = { list: [ 1, 2 ] };
const rhs = { list: [ 1, 3 ] };
const result = diff(lhs, rhs);
// Output often marks the entire 'list' key as changed
// { changed: { list: { from: [ 1, 2 ], to: [ 1, 3 ] } } }
The longevity and support of a library matter for long-term projects.
deep-diff is stable and widely used.
jsondiffpatch is actively maintained with extras.
object-diff has low activity.
| Feature | deep-diff | jsondiffpatch | object-diff |
|---|---|---|---|
| Output Type | Array of edits | Delta object | Simple change object |
| Apply Patch | ✅ Yes (applyDiff) | ✅ Yes (patch) | ❌ No (Manual) |
| Reverse Diff | ❌ No | ✅ Yes (reverse) | ❌ No |
| Array Handling | Index-based | Smart mapping | Basic/Whole value |
| Visualizer | ❌ No | ✅ Yes | ❌ No |
| Maintenance | 🟢 Active | 🟢 Active | 🟡 Low |
For most professional frontend architectures, jsondiffpatch is the strongest choice. It handles arrays intelligently, supports patching and reversing, and offers tools like visualizers that save development time. It is built for data synchronization.
Use deep-diff if your primary goal is logging or auditing. The array output is easier to iterate over for generating human-readable reports like "User changed field X from Y to Z".
Avoid object-diff for new projects unless you have a strict constraint against larger dependencies. Its lack of patching support and basic array handling makes it less suitable for modern state management needs.
Choose deep-diff if you need a detailed, human-readable log of changes represented as an array of edits. It is ideal for debugging tools, audit logs, or scenarios where you need to iterate over changes programmatically. It handles arrays and nested objects well but does not focus on compressing diffs for transmission.
Choose jsondiffpatch if you need to store, transmit, or apply diffs efficiently. It creates a compact delta object that mirrors the original structure, making it perfect for operational transformation or syncing state. It also offers a visualizer and robust array mapping, which is critical for complex JSON data.
Choose object-diff only for simple, shallow comparisons in legacy projects or scripts where dependencies must be minimal. It returns a straightforward object of added, removed, and changed keys. However, it lacks advanced features like array indexing or patch application, and maintenance is less active than the other options.
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!