diff
Javascript utility for calculating deep difference, capturing changes, and applying changes across objects; for nodejs and the browser.
Top Related Projects
Diff & patch JavaScript objects
Diff Match Patch is a high-performance library in multiple languages that manipulates plain text.
A javascript text differencing implementation.
Quick Overview
flitbit/diff is a JavaScript library for calculating deep differences between two objects. It provides a simple and efficient way to compare complex nested structures and identify changes, additions, and deletions between them.
Pros
- Handles deep object comparisons efficiently
- Supports custom comparison functions for specific object types
- Lightweight with no external dependencies
- Works in both Node.js and browser environments
Cons
- Limited documentation and examples
- Not actively maintained (last update was several years ago)
- May not handle circular references well
- Performance can degrade with extremely large or deeply nested objects
Code Examples
Comparing two simple objects:
const diff = require('deep-diff').diff;
const obj1 = { a: 1, b: { c: 2 } };
const obj2 = { a: 1, b: { c: 3 }, d: 4 };
const differences = diff(obj1, obj2);
console.log(differences);
Using a custom comparison function:
const diff = require('deep-diff').diff;
const customDiff = (path, key) => {
if (key === 'timestamp') return () => {};
return diff;
};
const obj1 = { id: 1, timestamp: 1234567890 };
const obj2 = { id: 1, timestamp: 9876543210 };
const differences = diff(obj1, obj2, customDiff);
console.log(differences);
Applying changes to an object:
const { diff, applyChange } = require('deep-diff');
const obj1 = { a: 1, b: { c: 2 } };
const obj2 = { a: 1, b: { c: 3 }, d: 4 };
const differences = diff(obj1, obj2);
differences.forEach(change => {
applyChange(obj1, obj2, change);
});
console.log(obj1); // Now obj1 is identical to obj2
Getting Started
To use flitbit/diff in your project, follow these steps:
-
Install the package:
npm install deep-diff
-
Import the library in your JavaScript file:
const { diff, applyDiff, observableDiff } = require('deep-diff');
-
Use the
diff
function to compare objects:const differences = diff(object1, object2); console.log(differences);
Competitor Comparisons
Diff & patch JavaScript objects
Pros of jsondiffpatch
- More comprehensive diffing capabilities, including array diffing and moving detection
- Supports visual diff rendering in HTML
- Offers bidirectional diffing and patching
Cons of jsondiffpatch
- Larger package size and potentially more complex to use
- May have slower performance for simple object comparisons
- Less actively maintained (last update in 2021)
Code Comparison
jsondiffpatch:
var jsondiffpatch = require('jsondiffpatch');
var delta = jsondiffpatch.diff(obj1, obj2);
var patched = jsondiffpatch.patch(obj1, delta);
var reverseDelta = jsondiffpatch.reverse(delta);
diff:
var diff = require('flitbit/diff');
var delta = diff(obj1, obj2);
var patched = diff.apply(obj1, delta);
Key Differences
- jsondiffpatch offers more advanced features like array diffing and visual rendering
- diff is simpler and more lightweight, focusing on basic object comparison
- jsondiffpatch provides bidirectional diffing and patching, while diff is unidirectional
- diff has more recent updates and active maintenance
- jsondiffpatch may be better suited for complex JSON structures, while diff is ideal for simpler object comparisons
Both libraries serve the purpose of comparing JavaScript objects, but they cater to different use cases and complexity levels. The choice between them depends on the specific requirements of your project, such as the need for advanced diffing features, performance considerations, and maintenance preferences.
Diff Match Patch is a high-performance library in multiple languages that manipulates plain text.
Pros of diff-match-patch
- Supports multiple programming languages (C++, Java, JavaScript, Lua, Objective C, Python)
- Offers more advanced features like fuzzy matching and patch application
- Well-documented with extensive examples and explanations
Cons of diff-match-patch
- More complex API, potentially steeper learning curve
- Larger codebase, which may impact performance for simple diff operations
- Last updated in 2018, potentially less active maintenance
Code Comparison
diff-match-patch:
dmp = new diff_match_patch();
diff = dmp.diff_main('Hello World.', 'Goodbye World.');
dmp.diff_cleanupSemantic(diff);
diff:
var diff = require('flitbit/diff');
var result = diff({ a: 'Hello World.' }, { a: 'Goodbye World.' });
Summary
diff-match-patch offers a more comprehensive solution with support for multiple languages and advanced features, making it suitable for complex diff operations. However, it may be overkill for simple use cases. diff provides a simpler API and focuses on JavaScript, making it easier to use for basic object comparison tasks. The choice between the two depends on the specific requirements of your project, such as language support, feature needs, and complexity tolerance.
A javascript text differencing implementation.
Pros of jsdiff
- More actively maintained with recent updates
- Supports a wider range of diff types (e.g., word, line, sentence)
- Better documentation and examples
Cons of jsdiff
- Larger file size and potentially higher memory usage
- May be overly complex for simple diffing needs
Code Comparison
diff:
var diff = require('diff');
var result = diff({a: 1}, {a: 2});
console.log(result);
jsdiff:
var jsdiff = require('diff');
var result = jsdiff.diffJson({a: 1}, {a: 2});
console.log(result);
Key Differences
- diff focuses on object and array differences
- jsdiff offers more granular diffing options (e.g., character-level diffs)
- diff returns a simpler output structure
- jsdiff provides more detailed information about changes
Use Cases
- diff: Ideal for simple object comparisons and basic diffing needs
- jsdiff: Better suited for complex text diffing, including line-by-line and word-by-word comparisons
Community and Support
- diff has fewer stars and contributors on GitHub
- jsdiff has a larger user base and more third-party resources available
Performance
- diff may be faster for simple object comparisons
- jsdiff might have better performance for large text diffs due to optimized algorithms
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
deep-diff
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.
Install
npm install deep-diff
Possible v1.0.0 incompatabilities:
- elements in arrays are now processed in reverse order, which fixes a few nagging bugs but may break some users
- If your code relied on the order in which the differences were reported then your code will break. If you consider an object graph to be a big tree, then
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.
- If your code relied on the order in which the differences were reported then your code will break. If you consider an object graph to be a big tree, then
Features
- Get the structural differences between two objects.
- Observe the structural differences between two objects.
- When structural differences represent change, apply change from one object to another.
- When structural differences represent change, selectively apply change from one object to another.
Installation
npm install deep-diff
Importing
nodejs
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';
browser
<script src="https://cdn.jsdelivr.net/npm/deep-diff@1/dist/deep-diff.min.js"></script>
In a browser,
deep-diff
defines a global variableDeepDiff
. If there is a conflict in the global namespace you can restore the conflicting definition and assigndeep-diff
to another variable like this:var deep = DeepDiff.noConflict();
.
Simple Examples
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
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 array
path
- 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 index
Change 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.
Changes
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);
}
});
API Documentation
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[, options, acc])
— calculates the differences between two objects, optionally using the specified accumulator.observableDiff(lhs, rhs, observer[, options])
— calculates the differences between two objects and reports each to an observer function.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.
diff
The diff
function calculates the difference between two objects.
Arguments
lhs
- the left-hand operand; the origin object.rhs
- the right-hand operand; the object being compared structurally with the origin object.options
- A configuration object that can have the following properties:prefilter
: function that determines whether difference analysis should continue down the object graph. This function can also replace theoptions
object in the parameters for backward compatibility.normalize
: function that pre-processes every leaf of the tree.
acc
- an optional accumulator/array (requirement is that it have apush
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.
}
Pre-filtering Object Properties
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');
Normalizing object properties
The normalize
's signature should be function(path, key, lhs, rhs)
and it should return either a falsy value if no normalization has occured, or a [lhs, rhs]
array to replace the original values. This step doesn't occur if the path was filtered out in the prefilter
phase.
const diff = require('deep-diff');
const assert = require('assert');
const data = {
pull: 149,
submittedBy: 'saveman71',
};
const clone = JSON.parse(JSON.stringify(data));
clone.issue = 42;
const two = diff(data, clone);
const none = diff(data, clone, {
normalize: (path, key, lhs, rhs) => {
if (lhs === 149) {
lhs = 42;
}
if (rhs === 149) {
rhs = 42;
}
return [lsh, rhs];
}
});
assert.equal(two.length, 1, 'should reflect one difference');
assert.ok(typeof none === 'undefined', 'should reflect no difference');
observableDiff
The observableDiff
function calculates the difference between two objects and reports each to an observer function.
Argmuments
lhs
- the left-hand operand; the origin object.rhs
- the right-hand operand; the object being compared structurally with the origin object.observer
- The observer to report to.options
- A configuration object that can have the following properties:prefilter
: function that determines whether difference analysis should continue down the object graph. This function can also replace theoptions
object in the parameters for backward compatibility.normalize
: function that pre-processes every leaf of the tree.
Contributing
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!
Top Related Projects
Diff & patch JavaScript objects
Diff Match Patch is a high-performance library in multiple languages that manipulates plain text.
A javascript text differencing implementation.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot