Last active
June 3, 2024 09:25
-
-
Save kcak11/70b7c8a5275e6bde466a5805235e2192 to your computer and use it in GitHub Desktop.
JavaScript Object DeepCompare
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
| <h1>Open your browser's console to view the output.</h1> | |
| <!-- | |
| © 2018 https://kcak11.com / https://ashishkumarkc.com | |
| --> |
Deep comparison of JavaScript objects.
A Pen by K.C.Ashish Kumar on CodePen.
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
| /** | |
| * 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)); |
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
| /* | |
| © 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