Smart Object Diff
A lightweight utility for performing deep comparison between JavaScript/TypeScript objects and identifying added, removed, or updated properties with their full paths.
Installation
npm install smart-object-diff
# or
yarn add smart-object-diff
Usage
Basic Usage
const smartDiff = require('smart-object-diff');
const obj1 = {
name: 'John',
age: 30,
address: {
city: 'New York',
country: 'USA'
}
};
const obj2 = {
name: 'John Doe',
age: 30,
address: {
city: 'Boston',
zip: '02108'
}
};
const changes = smartDiff(obj1, obj2);
console.log(changes);
Output Format
The function returns an array of changes, where each change has the following structure:
interface Change {
path: string; // Dot notation path to the changed property
type: 'added' | 'removed' | 'updated';
before: any; // Previous value (undefined for 'added')
after: any; // New value (undefined for 'removed')
}
Example output for the above code:
[
{
path: 'name',
type: 'updated',
before: 'John',
after: 'John Doe'
},
{
path: 'address.city',
type: 'updated',
before: 'New York',
after: 'Boston'
},
{
path: 'address.country',
type: 'removed',
before: 'USA',
after: undefined
},
{
path: 'address.zip',
type: 'added',
before: undefined,
after: '02108'
}
]
TypeScript Support
The package includes TypeScript type definitions out of the box:
import smartDiff from 'smart-object-diff';
// TypeScript will provide type hints for the changes
const changes = smartDiff(obj1, obj2);
Features
- Deep comparison of nested objects
- Tracks changes with full property paths
- Handles added, removed, and updated properties
- Lightweight with no external dependencies
- TypeScript support included
- Works in both Node.js and browser environments
License
MIT © Awais Manzoor