How to compare two JavaScript objects for equality


The Javascript === operator compares references to JavaScript objects and not the ‘deep’ data inside of them. With some searching, I found a useful utility function that will recursively evaluate 2 JSON objects for equality.  jQuery should have a utility function that does this.  I couldn’t find one.

var Utility = {
   areEqual: function(x, y) {
        for (var p in y) {
            if(typeof(y[p]) !== typeof(x[p])) return false;
            if((y[p]===null) !== (x[p]===null)) return false;
            switch (typeof(y[p])) {
                case 'undefined':
                    if (typeof(x[p]) != 'undefined') return false;
                    break;
                case 'object':
                    if(y[p]!==null && x[p]!==null && (y[p].constructor.toString() !== x[p].constructor.toString() || !y[p].equals(x[p]))) return false;
                    break;
                case 'function':
                    if (p != 'equals' && y[p].toString() != x[p].toString()) return false;
                    break;
                default:
                    if (y[p] !== x[p]) return false;
            }
        }
        return true;
 }

Usage:

var a = {'a':2, 'b':{}};
var b = {'a':2, 'b':{}};

if(Utility.areEqual(a,b)) {
    alert('It worked!');
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s