12

Possible Duplicate:
Object comparison in JavaScript

I have two native JavaScript objects:

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

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

Community
  • 1
  • 1
Russell
  • 935
  • 5
  • 13
  • 27
  • There is a discussion about this here: [http://stackoverflow.com/questions/1068834/object-comparison-in-javascript](http://stackoverflow.com/questions/1068834/object-comparison-in-javascript) – fehays Sep 24 '10 at 22:51

2 Answers2

6

This works well, but only in some cases:

var obj1 = {n1: "v1", n2: "v2"},
    obj2 = {n1: "v1", n2: "v2"},
    obj3 = {n2: "v2", n1: "v1"},
    obj4 = {n2: "v2", n1: "v1", f: function(){}};


// this will work correctly:
JSON.stringify(obj1) == JSON.stringify(obj2); //true


// but this fails :(
JSON.stringify(obj2) == JSON.stringify(obj3); //false


// and this :(
JSON.stringify(obj3) == JSON.stringify(obj4); //true
Dan
  • 55,715
  • 40
  • 116
  • 154
Joe
  • 85
  • 1
  • 2
  • 4
    Comparing objects with `JSON.stringify` will *only sometimes* work because the order of the keys is not well-defined. The properties just happened to be iterated in the same order in this example - and in the particular implementation tested - but *this behavior is undefined and should not be used*. –  Oct 12 '12 at 02:54
  • I think this approach could be modified (e.g. serialize the object with keys in sorted order) to address the problem described by pst, couldn't it? – jacobq Mar 06 '13 at 15:42
  • 1
    Following @user166390. This method works ONLY if the object contains no Functions, DOM nodes, and the order of the fields remains the same. It works when comparing JSONs from some API. But, if you compare objects created by yourself, WHY NOT USE A UNIQUE ID? – Dan Jun 26 '13 at 07:32
1

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
  • 7,637
  • 9
  • 53
  • 71