Compare to ojbects in Javascript


Here is a java script routine to compare two objects. This will also compare function pointers. If you want to ignore functions then use Object.prototype.toString.call(obj_1[entry]) == "[object Function]" and Object.prototype.toString.call(obj_2[entry]) == "[object Function]" to test for functions

function compareObjects(obj_1, obj_2){
    var isEqual = true; //Assume true until proven false
    if (typeof obj_1 != "object" || typeof obj_2 != "object"){ //If either one is not an object do a simple compare
        if (obj_1 != obj_2)isEqual = false
    } else {
        var entry;
        for (entry in obj_1){
            if (entry != null && entry != undefined && entry.length!=0){
                if (typeof obj_1[entry] == "object"){ //If entry is an object then recurse
                    if (compareObjects(obj_1[entry], obj_2[entry])==false){
                        isEqual = false;
                        break;
                    }
                } else {
                    if (obj_1[entry] != obj_2[entry]){
                        isEqual = false;
                        break;
                    }
                }
            }
        }
        if (isEqual){ //If everything in obj_1 is in obj_2 then verify that the reverse is also true
            for (entry in obj_2){
                if (entry != null && entry != undefined && entry.length!=0){
                    if (typeof obj_2[entry] == "object"){
                        if (compareObjects(obj_1[entry], obj_2[entry])==false){
                            isEqual = false;
                            break;
                        }
                    } else {
                        if (obj_1[entry] != obj_2[entry]){
                            isEqual = false;
                            break;
                        }
                    }
                }
            }
        }
    }
    return isEqual;
}


Lee Lofgren
Last Modified 04/01/2011