A strict equality operator will tell you if two object types are equal. However, is there a way to tell if two objects are equal, much like the hash code value in Java?
Stack Overflow question Is there any kind of hashCode function in JavaScript? is similar to this question, but requires a more academic answer. The scenario above demonstrates why it would be necessary to have one, and I'm wondering if there is any equivalent solution.
For comparing keys for simple key/value pairs object instances, I use:
Once keys are compared, a simple additional
for..in
loop is enough.Complexity is O(N*N) with N is the number of keys.
I hope/guess objects I define won't hold more than 1000 properties...
Needing a more generic object comparison function than had been posted, I cooked up the following. Critique appreciated...
In Node.js, you can use its native
require("assert").deepEqual
. More info: http://nodejs.org/api/assert.htmlFor example:
Another example that returns
true
/false
instead of returning errors:There is a very simple fix for this one, all you have to do is JSON.stringify() on both of the objects when you compare the two.
A simple solution to this issue that many people don't realize is to sort the JSON strings (per character). This is also usually faster than the other solutions mentioned here:
Another useful thing about this method is you can filter comparisons by passing a "replacer" function to the JSON.stringify functions (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#Example_of_using_replacer_parameter). The following will only compare all objects keys that are named "derp":
you can use
_.isEqual(obj1, obj2)
from the underscore.js library.Here is an example:
See the official documentation from here: http://underscorejs.org/#isEqual