Skip to content

Instantly share code, notes, and snippets.

@patrickisgreat
Created May 30, 2024 16:08
Show Gist options
  • Save patrickisgreat/e32cfd87e24cd2b4d1fe229e22b41188 to your computer and use it in GitHub Desktop.
Save patrickisgreat/e32cfd87e24cd2b4d1fe229e22b41188 to your computer and use it in GitHub Desktop.
Deep Object Diffing
function deepDiff(obj1, obj2) {
function changes(obj1, obj2) {
let diff = {};
for (let key in obj1) {
if (obj2.hasOwnProperty(key)) {
if (typeof obj1[key] === 'object' && typeof obj2[key] === 'object') {
let deepChanges = changes(obj1[key], obj2[key]);
if (Object.keys(deepChanges).length > 0) {
diff[key] = deepChanges;
}
} else if (obj1[key] !== obj2[key]) {
diff[key] = { oldValue: obj1[key], newValue: obj2[key] };
}
} else {
diff[key] = { oldValue: obj1[key], newValue: undefined };
}
}
for (let key in obj2) {
if (!obj1.hasOwnProperty(key)) {
diff[key] = { oldValue: undefined, newValue: obj2[key] };
}
}
return diff;
}
return changes(obj1, obj2);
}
const lhs = { a: 1, b: 2, c: { d: 3 } };
const rhs = { a: 1, b: 3, c: { d: 4 } };
const differences = deepDiff(lhs, rhs);
console.log(differences);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment