Created
June 26, 2017 15:53
-
-
Save gudnm/34135a5987fa9efeac7c813bcbe2f4b9 to your computer and use it in GitHub Desktop.
JavaScript function for checking if two objects are equal by value
This file contains 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
var objectsEqual = (a, b) => { | |
const aProps = Object.getOwnPropertyNames(a), | |
bProps = Object.getOwnPropertyNames(b); | |
if (aProps.length != bProps.length) { | |
return false; | |
} | |
for (var i=0; i<aProps.length; i++) { | |
const propName = aProps[i]; | |
// check for NaN's | |
if (a[propName] != a[propName]) { | |
if (b[propName] != b[propName]) { | |
continue; | |
} | |
return false; | |
} | |
// do a recursive check if property value is an object | |
if (typeof(a[propName]) === 'object') { | |
if (typeof(b[propName]) === 'object' && objectsEqual(a[propName], b[propName])) { | |
continue; | |
} | |
return false; | |
} | |
// otherwise compare values | |
if (a[propName] !== b[propName]) { | |
return false; | |
} | |
} | |
return true; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment