Skip to content

Instantly share code, notes, and snippets.

@tcdevs
Forked from nicbell/1_primitive_comparison.js
Created January 5, 2017 08:27
Show Gist options
  • Save tcdevs/8df72232e83e6c7d4a3979c2e13dd8e6 to your computer and use it in GitHub Desktop.
Save tcdevs/8df72232e83e6c7d4a3979c2e13dd8e6 to your computer and use it in GitHub Desktop.
JavaScript object deep comparison. Comparing x === y, where x and y are values, return true or false. Comparing x === y, where x and y are objects, returns true if x and y refer to the same object. Otherwise, returns false even if the objects appear identical. Here is a solution to check if two objects are the same.
Object.compare = function (obj1, obj2) {
//Loop through properties in object 1
for (var p in obj1) {
//Check property exists on both objects
if (obj1.hasOwnProperty(p) !== obj2.hasOwnProperty(p)) return false;
switch (typeof (obj1[p])) {
//Deep compare objects
case 'object':
if (!Object.compare(obj1[p], obj2[p])) return false;
break;
//Compare function code
case 'function':
if (typeof (obj2[p]) == 'undefined' || (p != 'compare' && obj1[p].toString() != obj2[p].toString())) return false;;
break;
//Compare values
default:
if (obj1[p] != obj2[p]) return false;
}
}
//Check object 2 for any extra properties
for (var p in obj2) {
if (typeof (obj1[p]) == 'undefined') return false;
}
return true;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment