@phragon-util/diff
is a JavaScript library designed to find and represent differences between two objects.
It supports deep comparison of nested objects and arrays, providing an easy way to identify changes.
You can install @phragon-util/diff
via npm or yarn.
npm install @phragon-util/diff
yarn add @phragon-util/diff
The library can be used with both ES Modules (ESM) and CommonJS.
import { diff } from '@phragon-util/diff';
const { diff } = require('@phragon-util/diff');
declare function diff<T extends object>(a: T, b: T, options?: DiffOptions): Diff[]
Compares two objects and returns an array of differences.
-
a
(T): The first object to compare. -
b
(T): The second object to compare. -
options
(DiffOptions
, optional): Configuration options for the comparison.
-
ignore
(string[]
, optional): List of properties to ignore during comparison. Nested property names should be dot-separated (e.g.,'parent.child'
). -
depth
(number
, optional): The maximum depth for displaying the differences in the result.
The depth controls how many levels of nested properties are included in theDiff
array. A depth of 2 will show differences up to depth 2, even if changes are found at deeper levels. The comparison itself is done fully regardless of this setting. Arrays always show differences up to the first level inside the array.
The maximum depth of nested properties to include in the output. If not specified, the default depth is 3.
-
Diff[]
: An array of differences. Each difference includes the name, path, type, from value, and to value.
Type for the type of difference:
-
"N"
: Indicates a newly added property/element. -
"D"
: Indicates a property/element was deleted. -
"E"
: Indicates a property/element was edited.
In this example:
The depth option limits the depth of the properties shown in the diff result to 2 levels deep.
import { diff } from '@phragon-util/diff';
const obj1 = {
name: 'Alice',
age: 30,
address: {
city: 'Wonderland',
postalCode: '12345'
}
};
const obj2 = {
name: 'Alice',
age: 31,
address: {
city: 'Wonderland',
postalCode: '54321'
}
};
// depth 1
console.log(diff(obj1, obj2, { depth: 1 }));
// depth 2
console.log(diff(obj1, obj2, { depth: 2 }));
[
{
"name": "age",
"path": ["age"],
"type": "E",
"from": 30,
"to": 31
},
{
"name": "address",
"path": ["address"],
"type": "E",
"from": {
"city": "Wonderland",
"postalCode": "12345"
},
"to": {
"city": "Wonderland",
"postalCode": "54321"
}
}
]
[
{
"name": "age",
"path": ["age"],
"type": "E",
"from": 30,
"to": 31
},
{
"name": "address.postalCode",
"path": ["address", "postalCode"],
"type": "E",
"from": "12345",
"to": "54321"
}
]
This library is licensed under the MIT License. See the LICENSE file for more details.