Skip to content

Instantly share code, notes, and snippets.

@kcak11
Last active June 3, 2024 09:25
Show Gist options
  • Select an option

  • Save kcak11/70b7c8a5275e6bde466a5805235e2192 to your computer and use it in GitHub Desktop.

Select an option

Save kcak11/70b7c8a5275e6bde466a5805235e2192 to your computer and use it in GitHub Desktop.
JavaScript Object DeepCompare

JavaScript Object DeepCompare

<h1>Open your browser's console to view the output.</h1>
<!--
© 2018 https://kcak11.com / https://ashishkumarkc.com
-->
/**
* JavaScript Object Deep Comparison, Simple & Efficient
*
* Usage: deepCompareObjects(objA,objB);
* Returns true / false based on the comparison result
*
* Author: kcak11 --> github.com/kcak11
*/
function deepCompareObjects(a, b) {
return (a === b) ? true : (function() {
function objType(obj) {
return Object.prototype.toString.call(obj);
}
return (objType(a) !== objType(b)) ? false : (function() {
String.prototype.repAll = function(str, rep) {
var r = new RegExp(str,"g");
return this.replace(r, rep);
};
var rawA = getRaw(a);
var rawB = getRaw(b);
function getRaw(obj) {
try {
var json = JSON.stringify(obj) || "";
json = json.repAll("{", "^").repAll(",", "^").repAll("}", "^").repAll(":", "^");
return json.split("^").sort().join("^");
} catch (exjs) {
return false;
}
}
return rawA === rawB;
}());
}());
}
//Usage:
var obj1 = {
a: "xyz",
b: "pqr",
c: {
key1: "value1",
key2: ["a1", "a2"]
}
};
var obj2 = {
b: "pqr",
c: {
key2: ["a1", "a2"],
key1: "value1"
},
a: "xyz"
};
console.log("Objects are equal: " + deepCompareObjects(obj1, obj2));
/*
© 2018 https://kcak11.com / https://ashishkumarkc.com
*/
body {
font-family: Verdana;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment