views:

61

answers:

3

I have two native JavaScript objects:

var foo = { hello: 'world', holy: { shit: 'batman' } };
var bar = { ... };

I would like to compare the two (foo == bar).

A: 

What exactly do you need to compare? You should be able to check if they're equal or not with the == operator.

Filipe
No I don't think that works - console.log(foo == bar); prints "false". bar is identical to foo in my test, not var bar = { ... };
roosta
No, because objects are compared by reference; i.e., if you assign `var bar = foo` and then change `foo`, the same properties in `bar` are changed and you still get `bar == foo`.
Marcel Korpel
A: 

jQuery has no built-in utility for comparing objects. It's not really clear from your post what information you want to derive from your two objects. Are you trying to sort them?

Depending on what you are trying to do, you may be able to satisfy your use case by using one of jQuery's utility methods, though. See, for example: jQuery.extend, jQuery.each, jQuery.map, and jQuery.merge. jQuery is primarily concerned with manipulating DOM elements; it doesn't have a built-in feature for list sorting (though you may be able to find a plugin).

Check out the jQuery utilities documentation:

http://api.jquery.com/category/utilities/

Also, check out array.sort(), which apparently is built into javascript:

http://www.javascriptkit.com/javatutors/arraysort.shtml

RMorrisey
+1  A: 

There is a discussion about this here:

http://stackoverflow.com/questions/1068834/object-comparison-in-javascript

fehays
i'd say these are duplicates
Claudiu
This should be a comment to the original post, not an answer.
Marcel Korpel