What is the best way to compare objects in JavaScript ?
Solution 1:
Unfortunately there is no perfect way, unless we use _proto_ recursively and access all non-enumerable properties, but this works in Firefox only.
So the best We can do is to guess usage scenarios.
1) Fast and limited.
Works when we have simple JSON-style objects without methods and DOM nodes inside:
The ORDER of the properties IS IMPORTANT, so this method will return false for following objects:
2) Slow and more generic.
Compares objects without digging into prototypes, then compares properties' projections recursively, and also compares constructors.
This is almost correct algorithm:
Known issues (well, they have very low priority, probably you'll never notice them):
objects with different prototype structure but same projection
functions may have identical text but refer to different closures
Solution 2:
Here is my commented solution (gory details after the code):
In developing this solution, We took a particular look at corner cases, efficiency, yet trying to yield a simple solution that works, hopefully with some elegance.
JavaScript allows both null and undefined properties and objects have prototypes chains that can lead to very different behaviors if not checked.
First We have chosen to extend Object instead of Object.prototype, mostly because null could not be one of the objects of the comparison and that We believe that null should be a valid object to compare with another.
There are also other legitimate concerns noted by others regarding the extension of Object.prototype regarding possible side effects on other's code.
Special care must taken to deal the possibility that JavaScript allows object properties can be set to undefined, i.e. there exists properties which values are set to undefined.
The above solution verifies that both objects have the same properties set to undefined to report equality.
This can only be accomplished by checking the existence of properties using Object.hasOwnProperty( property_name ).
Also note that JSON.stringify() removes properties that are set to undefined, and that therefore comparisons using this form will ignore properties set to the value undefined.
Functions should be considered equal only if they share the same reference, not just the same code, because this would not take into account these functions prototype.
So comparing the code string does not work to guaranty that they have the same prototype object.
The two objects should have the same prototype chain, not just the same properties.
This can only be tested cross-browser by comparing the constructor of both objects for strict equality.
ECMAScript 5 would allow to test their actual prototype using Object.getPrototypeOf(). Some web browsers also offer a __proto__ property that does the same thing. A possible improvement of the above code would allow to use one of these methods whenever available.
The use of strict comparisons is paramount here because 2 should not be considered equal to "2.0000", nor false should be considered equal to null, undefined, or 0.
Efficiency considerations lead me to compare for equality of properties as soon as possible.
Then, only if that failed, look for the typeof these properties. The speed boost could be significant on large objects with lots of scalar properties.
No more that two loops are required, the first to check properties from the left object, the second to check properties from the right and verify only existence (not value), to catch these properties which are defined with the undefined value.
Overall this code handles most corner cases in only 16 lines of code (without comments).
We have implemented a better version, as the function value_equals() that is faster, handles properly corner cases such as NaN and 0 different than -0, optionally enforcing objects' properties order and testing for cyclic references, backed by more than 100 automated tests as part of the Toubkal project test suite
Solution 3:
Certainly not the only way - we could prototype a method (against Object here but We certainly wouldn't suggest using Object for live code) to replicate C#/Java style comparison methods.
Edit, since a general example seems to be expected:
Note that testing methods with toString() is absolutely not good enough but a method which would be acceptable is very hard because of the problem of whitespace having meaning or not, never mind synonym methods and methods producing the same result with different implementations. And the problems of prototyping against Object in general.
Solution 4:
Solution 5:
We wrote this piece of code for object comparison, and it seems to work. check the assertions: