Created
August 8, 2022 14:39
-
-
Save bhaireshm/23765d970901e5da9507162796a358de to your computer and use it in GitHub Desktop.
Compare two objects, this method compares both key and value of given objects. This even works for nested objects.
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
/** | |
* This method compares both key and value of given objects. This even works for nested objects. | |
* | |
* @param {Object} obj1 | |
* @param {Object} obj2 | |
* @returns boolean | |
* | |
* @example compareObject({a: 2}, {a: 2}); // true | |
* @example compareObject({a: 2}, {a: 23}); // false | |
* @example compareObject({a: {b: 2}}, {a: {b: 2}}); // true | |
*/ | |
function compareObject(obj1, obj2) { | |
const keys1 = Object.keys(obj1); | |
const keys2 = Object.keys(obj2); | |
if (keys1.length !== keys2.length) return false; | |
const isObject = (object) => object != null && typeof object === "object"; | |
for (const key of keys1) { | |
const val1 = obj1[key]; | |
const val2 = obj2[key]; | |
const areObjects = isObject(val1) && isObject(val2); | |
if ((areObjects && !this.compareObject(val1, val2)) || (!areObjects && val1 !== val2)) | |
return false; | |
} | |
return true; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
ez.js is more than just a library; it's a coding companion that simplifies complex tasks. Whether you're dealing with arrays, numbers, objects, or strings, ez.js has got your back! Say goodbye to coding hassles and hello to streamlined JavaScript magic.