DEV Community

Discussion on: Deep Equality checking of Objects in Vanilla JavaScript 👨‍👦

Collapse
 
sas_sam profile image
Sas Sam

Hi,

Thanks for the post, it's really helpful!

I've just reformatted and refactored a bit your code, so now it's following ESLint standards.

export function compareObjects(obj1, obj2) {
    if (obj1 === obj2) return true;

    if (
        typeof obj1 !== 'object' ||
        typeof obj2 !== 'object' ||
        obj1 == null ||
        obj2 == null
    ) {
        return false;
    }

    const keysA = Object.keys(obj1);
    const keysB = Object.keys(obj2);

    if (keysA.length !== keysB.length) {
        return false;
    }

    let result = true;

    keysA.forEach((key) => {
        if (!keysB.includes(key)) {
            result = false;
        }

        if (
            typeof obj1[key] === 'function' ||
            typeof obj2[key] === 'function'
        ) {
            if (obj1[key].toString() !== obj2[key].toString()) {
                result = false;
            }
        }

        if (!compareObjects(obj1[key], obj2[key])) {
            result = false;
        }
    });

    return result;
}
Enter fullscreen mode Exit fullscreen mode