Skip to content

Instantly share code, notes, and snippets.

@bhaireshm
Created August 8, 2022 14:39
Show Gist options
  • Save bhaireshm/23765d970901e5da9507162796a358de to your computer and use it in GitHub Desktop.
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 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;
};
@bhaireshm
Copy link
Author

bhaireshm commented Feb 24, 2025

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment