Skip to content

Instantly share code, notes, and snippets.

@krystalcampioni
Last active January 3, 2025 15:42
Show Gist options
  • Save krystalcampioni/2f94f5edfb99905833448af37245afe7 to your computer and use it in GitHub Desktop.
Save krystalcampioni/2f94f5edfb99905833448af37245afe7 to your computer and use it in GitHub Desktop.
Get the differences between two similar objects, like a git diff
import {isEqual, transform, isObject} from 'lodash';
interface Diff {
base: any;
comparison: any;
}
/**
* Get the differences between two objects.
* @param base - The base object.
* @param comparison - The comparison object.
* @returns The differences between the two objects.
*/
function getDifferences(
base: Object,
comparison: Object,
): Diff | 'No differences found' {
const diffs: Diff = {
base: {},
comparison: {},
};
transform(
base,
(result, value, key) => {
if (!isEqual(value, comparison[key])) {
if (isObject(value) && isObject(comparison[key])) {
const nestedDiffs = getDifferences(value, comparison[key]);
if (nestedDiffs !== 'No differences found') {
result.base[key] = nestedDiffs.base;
result.comparison[key] = nestedDiffs.comparison;
}
} else {
result.base[key] = value;
result.comparison[key] = comparison[key];
}
}
},
diffs,
);
return Object.keys(diffs.base).length === 0 ? 'No differences found' : diffs;
}
const obj1 = { a: 1, b: { c: 2, d: 3 }, e: 4 }
const obj2 = { a: 1, b: { c: 2, d: 5 }, e: 6 }
console.log(getDifferences(obj1, obj2));
// Outputs:
//
// {
// base: {
// b: { d: 3 },
// e: 4
// },
// comparison: {
// b: { d: 5 },
// e: 6
// }
// }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment