deep-diff-check v1.0.2
deep-diff-check
deep-diff-check is a lightweight utility that recursively finds and returns the differences between two JavaScript objects or arrays. This can be very useful for state comparisons, logging changes, or building synchronization features.
Table of Contents
Installation
Install the package using npm:
npm install deep-diff-check
Or yarn:
yarn add deep-diff-check
Usage
Below is a quick example demonstrating how to import and use deepDiff.
const deepDiff = require('deep-diff-check');
const objA = {
name: 'Alice',
age: 30
};
const objB = {
name: 'Bob',
age: 31
};
const differences = deepDiff(objA, objB);
console.log(differences);
/*
{
name: {
oldValue: "Alice",
newValue: "Bob"
},
age: {
oldValue: 30,
newValue: 31
}
}
*/
API Reference deepDiff(obj1, obj2) Parameters: obj1 (any): First object or value to compare. obj2 (any): Second object or value to compare. Returns: An object representing the differences, or undefined if there are no differences. Details:
If both parameters are objects (or arrays), the function performs a recursive check to find any nested differences. If they differ in type or structure, it returns the direct difference. Primitive comparison (string, number, boolean, etc.) is done by a simple !== check. Examples Object Differences
const obj1 = {
a: 1,
b: { x: 10, y: 20 },
c: ['hello']
};
const obj2 = {
a: 2,
b: { x: 15, y: 20 },
d: 'newKey'
};
console.log(deepDiff(obj1, obj2));
/*
{
a: { oldValue: 1, newValue: 2 },
b: { x: { oldValue: 10, newValue: 15 } },
c: { oldValue: ["hello"], newValue: undefined },
d: { oldValue: undefined, newValue: "newKey" }
}
*/
Array Differences
const arr1 = [1, 2, 3];
const arr2 = [1, 4, 3];
console.log(deepDiff(arr1, arr2));
/*
{
1: { oldValue: 2, newValue: 4 }
}
*/