Created
May 30, 2024 16:08
-
-
Save patrickisgreat/e32cfd87e24cd2b4d1fe229e22b41188 to your computer and use it in GitHub Desktop.
Deep Object Diffing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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