Created
May 3, 2022 01:10
-
-
Save kig/2470596b7d56c862e0932fb715e547fa to your computer and use it in GitHub Desktop.
JS Object diff function
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
const objDiff = (a, b) => { | |
if (typeof a === typeof b && typeof a === 'object') { | |
const diff = {}; | |
let changed = false; | |
for (let i in a) { | |
if (!b.hasOwnProperty(i)) { | |
diff[i] = 'DELETED'; | |
changed = true; | |
continue; | |
} | |
const d = objDiff(a[i], b[i]); | |
if (d !== undefined) { | |
diff[i] = d; | |
changed = true; | |
} | |
} | |
for (let i in b) { | |
if (!a.hasOwnProperty(i)) { | |
diff[i] = b[i]; | |
changed = true; | |
} | |
} | |
if (changed) return diff; | |
} else if (a !== b) return b; | |
return undefined; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment