Created
January 5, 2022 22:06
-
-
Save sharjeel619/7e852de35441740d4dc4b4fc525c4920 to your computer and use it in GitHub Desktop.
Deep compare two objects in javascript
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
// https://www.30secondsofcode.org/articles/s/javascript-object-comparison | |
const equals = (a, b) => { | |
if (a === b) return true; | |
if (a instanceof Date && b instanceof Date) | |
return a.getTime() === b.getTime(); | |
if (!a || !b || (typeof a !== 'object' && typeof b !== 'object')) | |
return a === b; | |
if (a.prototype !== b.prototype) return false; | |
const keys = Object.keys(a); | |
if (keys.length !== Object.keys(b).length) return false; | |
return keys.every(k => equals(a[k], b[k])); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment