How to check two objects are equal in javascript
Unfortunately there is no perfect way, unless you use Show So the best I can do is to guess usage scenarios. 1) Fast and limited.Works when you 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):
Tests: passes tests are from How to determine equality for two JavaScript objects?.
answered Jul 17, 2009 at 16:08
7 Here is my ES3 commented solution (gory details after the code):
In developing this solution, I 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 I have chosen to not extend Object.prototype, mostly because null could not be one of the objects of the comparison and that I 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). Update (8/13/2015). I 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. answered Jul 15, 2011 at 22:21
Jean VincentJean Vincent 11.4k7 gold badges32 silver badges24 bronze badges 0
Simple way to compare ONE-LEVEL only objects. answered May 2, 2011 at 15:27
pincopallopincopallo 6235 silver badges2 bronze badges 1 Certainly not the only way - you could prototype a method (against Object here but I 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. answered Jul 1, 2009 at 12:25
annakataannakata 73.1k16 gold badges113 silver badges180 bronze badges 0 The following algorithm will deal with self-referential data structures, numbers, strings, dates, and of course plain nested javascript objects: Objects are considered equivalent when
Functions are not considered identical by function text. This test is insufficient because functions may have differing closures. Functions are only
considered equal if Infinite loops, potentially caused by circular datastructures, are avoided. When
answered Jun 19, 2011 at 14:29
Eamon NerbonneEamon Nerbonne 45.7k19 gold badges95 silver badges165 bronze badges 1 I wrote this piece of code for object comparison, and it seems to work. check the assertions:
answered Oct 3, 2010 at 11:01
mhomsmhoms 1791 silver badge6 bronze badges 1 I have modified a bit the code above. for me 0 !== false and null !== undefined. If you do not need such strict check remove one "=" sign in "this[p] !== x[p]" inside the code.
Then I have tested it with next objects:
a==b expected true; returned true a==c expected false; returned false c==d expected false; returned false a==e expected false; returned false f==g expected true; returned true h==g expected false; returned false i==j expected true; returned true d==k expected false; returned false k==l expected false; returned false answered Apr 29, 2010 at 9:17
1 Here is my version, pretty much stuff from this thread is integrated (same counts for the test cases):
Here is my TestCase:
answered Apr 2, 2011 at 11:39
gossigossi 5445 silver badges16 bronze badges 3 If you work without the JSON library, maybe this will help you out:
answered Mar 9, 2010 at 10:38
2 if you want to check for methods explicitly you can use the method.toSource() or method.toString() methods. answered Jul 1, 2009 at 15:44
Nicolas RNicolas R 9622 gold badges8 silver badges17 bronze badges 5 Can you check if two objects are equal JavaScript?In JavaScript, we cannot directly compare two objects by equality operators (double equals == or triple equals ===) to see whether they are equal or not. Comparing two objects like this results in false even if they have the same data.
How do you know if objects are equal?If the two objects have the same values, equals() will return true . In the second comparison, equals() checks to see whether the passed object is null, or if it's typed as a different class. If it's a different class then the objects are not equal. Finally, equals() compares the objects' fields.
How do you compare two things in JavaScript?Comparing objects is easy, use === or Object.is(). This function returns true if they have the same reference and false if they do not. Again, let me stress, it is comparing the references to the objects, not the keys and values of the objects. So, from Example 3, Object.is(obj1,obj2); would return false.
How can I compare two objects?Difference Between == Operator and equals() Method
Whereas the equals() method compares two objects. Objects are equal when they have the same state (usually comparing variables). Objects are identical when they share the class identity. For example, the expression obj1==obj2 tests the identity, not equality.
|