What is the best way to compare objects in JavaScript?
Example:
var user1 = {name : "nerd", org: "dev"};
var user2 = {name : "nerd", org: "dev"};
var eq = user1 == user2;
alert(eq); // gives false
I know that two objects are equal if they refer to the exact same object, but is there a way to check if they have the same attributes’ values?
The following way works for me, but is it the only possibility?
var eq = Object.toJSON(user1) == Object.toJSON(user2);
alert(eq); // gives true
Unfortunately there is no perfect way, unless you use
_proto_recursively and access all non-enumerable properties, but this works in Firefox only.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?.