Skip to content

Instantly share code, notes, and snippets.

@gudnm
Created June 26, 2017 15:53
Show Gist options
  • Save gudnm/34135a5987fa9efeac7c813bcbe2f4b9 to your computer and use it in GitHub Desktop.
Save gudnm/34135a5987fa9efeac7c813bcbe2f4b9 to your computer and use it in GitHub Desktop.
JavaScript function for checking if two objects are equal by value
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