I want to compare 2 arrays of objects in JavaScript code. The objects have 8 total properties, but each object will not have a value for each, and the arrays are never going to be any larger than 8 items each, so maybe the brute force method of traversing each and then looking at the values of the 8 properties is the easiest way to do what I want to do, but before implementing, I wanted to see if anyone had a more elegant solution. Any thoughts?
feedback
|
EDIT: You cannot overload operators in current, common browser-based implementations of JavaScript interpreters. To answer the original question, one way you could do this, and mind you, this is a bit of a hack, simply serialize the two arrays to JSON and then compare the two JSON strings. That would simply tell you if the arrays are different, obviously you could do this to each of the objects within the arrays as well to see which ones were different. Another option is to use a library which has some nice facilities for comparing objects - I use and recommend MochiKit. EDIT: The answer kamens gave deserves consideration as well, since a single function to compare two given objects would be much smaller than any library to do what I suggest (although my suggestion would certainly work well enough). Here is a naïve implemenation that may do just enough for you - be aware that there are potential problems with this implementation:
The assumption is that both objects have the same exact list of properties. Oh, and it is probably obvious that, for better or worse, I belong to the only-one-return-point camp. :) | |||||||
feedback
|
Honestly, with 8 objects max and 8 properties max per object, your best bet is to just traverse each object and make the comparisons directly. It'll be fast and it'll be easy. If you're going to be using these types of comparisons often, then I agree with Jason about JSON serialization...but otherwise there's no need to slow down your app with a new library or JSON serialization code. | |||||
feedback
|
The objectsAreSame function mentioned in Jason's answer works fine for me. However, there's a little problem: If | |||
feedback
|
I have worked a bit on a simple algorithm to compare contents of two objects and return an intelligible list of difference. Thought I would share. It borrows some ideas for jQuery, namely the map function implementation and the object and array type checking. It returns a list of "diff objects", which are arrays with the diff info. It's very simple. Here it is:
| |||
feedback
|
I know this is an old question and the answers provided work fine ... but this is a bit shorter and doesn't require any additional libraries ( i.e. JSON ):
| |||||||||||||||
feedback
|