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.
If you have a deep copy function handy, you can use the following trick to still use
JSON.stringify
while matching the order of properties:Demo: http://jsfiddle.net/CU3vb/3/
Rationale:
Since the properties of
obj1
are copied to the clone one by one, their order in the clone will be preserved. And when the properties ofobj2
are copied to the clone, since properties already existing inobj1
will simply be overwritten, their orders in the clone will be preserved.I'm making the following assumptions with this function:
This should be treated as a demonstration of a simple strategy.
Are you trying to test if two objects are the equal? ie: their properties are equal?
If this is the case, you'll probably have noticed this situation:
you might have to do something like this:
Obviously that function could do with quite a bit of optimisation, and the ability to do deep checking (to handle nested objects:
var a = { foo : { fu : "bar" } }
) but you get the idea.As FOR pointed out, you might have to adapt this for your own purposes, eg: different classes may have different definitions of "equal". If you're just working with plain objects, the above may suffice, otherwise a custom
MyClass.equals()
function may be the way to go.I don't know if anyone's posted anything similar to this, but here's a function I made to check for object equalities.
Also, it's recursive, so it can also check for deep equality, if that's what you call it.
Pulling out from my personal library, which i use for my work repeatedly. The following function is a lenient recursive deep equal, which does not check
I mainly use this to check if i get equal replies against various API implementation. Where implementation difference (like string vs number) and additional null values, can occur.
Its implementation is quite straightforward and short (if all the comments is stripped off)
If you are comparing JSON objects you can use https://github.com/mirek/node-rus-diff
Usage:
If two objects are different, a MongoDB compatible
{$rename:{...}, $unset:{...}, $set:{...}}
like object is returned.