Comparing Javascript Objects

March 10, 2012

If you ever had the need to compare two javascript object you know that this is not an easy task. Javascript compare objects by reference, so only if it is the same object the javascript compare will return true.

The Problem

The simple solution to compare two object is to iterate on the properties and compare them. But then what if the object is nested?

Then we need to do that in a recursion until we get to a native literal. Sounds like we solve it. hmmm… not really, lets check the followings:

var obj1 = {a:1, b:2};
var obj2 = {a:1, b:2, c:3};

If we compare obj1 to obj2, which means we iterate on the obj1 properties and compare them to obj2 properties, then we will get that the objects are equal. But if we compare obj2 to obj1 we will get false, since obj1 doesn’t have the property ‘c’.

The Solution: Object-Helper

In order to solve this problem i created an helper file for object. at the moment it only implements isEqual to compare two objects, but maybe later i will add more object oriented tasks. The project is hosted in GitHub – Object-Helper

To solve the problem of asymmetric properties, I implemented an option to reverse the comparison. This means that the function will compare obj1 to obj2 and then will compare obj2 to obj1.

I had to develop it very quickly to solve a bug we had, so i didn’t took too much time to improve the efficiency of this method. That being said, while this solve the problem it introduce a new problem, efficiency. Since we are doing a reverse comparison and we have a recursions, it may result that the function will do more then one reverse to the same property.¬† This can increase the complexity to O(n*n) if not more.

This off course can be improved by checking which properties we have already reversed, or we can tell the function we don’t want the reverse to work. But if you don’t have huge JSON objects this should work fine.

 Exclude Me!

Another interesting feature that i implemented in this helper, is an exclude list that allows you to set which properties you don’t care about. Lets take to following example”

var obj1 = {a:1, b:2,created:1235433543};
var obj2 = {a:1, b:2, created:45343455443};

If we compere the two objects we will get false since created is not the same. But what if we don’t care when these objects were created? This is where you can use the exclude list like so:

isEqual( obj1, obj2, {
    exclude: { "created":true } } );

The exclude list is a map of properties names and a value must be set to true to indicate that this property needs to be excluded. The exclusion will be on any level in the Objects, so beware when using this feature.


For the full documentation and code samples check the source on GitHub.

Be Sociable, Share!

tags: ,
posted in Blog by Amir Harel

Powered by Wordpress and MySQL. Theme by