0

I need to compare 2 json objects like this: (This is a google chrome console output)

    Object {brand: "Marca A", type: "Tipo A", model: "Modelo A", color: "Color A", hand: "Mano A"…}
_id: "534664b081362062015d1b77"
brand: "Marca A"
color: "Color A"
hand: "Mano A"
model: "Modelo A"
price: "11,11"
type: "Tipo A"
__proto__: Object
__defineGetter__: function __defineGetter__() { [native code] }
__defineSetter__: function __defineSetter__() { [native code] }
__lookupGetter__: function __lookupGetter__() { [native code] }
__lookupSetter__: function __lookupSetter__() { [native code] }
constructor: function Object() { [native code] }
hasOwnProperty: function hasOwnProperty() { [native code] }
isPrototypeOf: function isPrototypeOf() { [native code] }
propertyIsEnumerable: function propertyIsEnumerable() { [native code] }
toLocaleString: function toLocaleString() { [native code] }
toString: function toString() { [native code] }
valueOf: function valueOf() { [native code] }
get __proto__: function __proto__() { [native code] }
set __proto__: function __proto__() { [native code] }

I had try with stringfy, angular.equals, underscore but always return me false..I want to do something more complex that compare one by one the fields of the Json, it its possible?

colymore
  • 11,776
  • 13
  • 48
  • 90
  • You can't use stringify because if there is two fields in diferents orders it will return false. You must to compare also the functions inside your object? – Alexandre TRINDADE Apr 24 '14 at 09:05

3 Answers3

3

angular.equals(o1, o2) should do the job, if the result is false, then some of the properties are not equal.

xdazz
  • 158,678
  • 38
  • 247
  • 274
1

Is an overstructure, but is very helpful, try to integrate "underscore" on your project, to compare objects you can use http://underscorejs.org/#isEqual.

Lucio Paoletti
  • 371
  • 2
  • 11
-1

The easiest way to do this is to use Stringify JSON.stringify which changes the objects to strings and compares them.

function isSame(o1, o2)
{
    return JSON.stringify(o1) !== JSON.stringify(o2);
}

However this method will fail for equal JSON objects where the structure is different, like:

JSON.stringify({a:1,b:2}) == JSON.stringify({b:2,a:1}) // returns false

To solve this problem you can use a deep compare as shown in the answer at Object comparison in JavaScript

But instead of re-inventing the wheel, you can also use underscore.js. It has a function isEqual() that compare objects.

_.isEqual(o1, o2);
Community
  • 1
  • 1
Joshua Kissoon
  • 3,269
  • 6
  • 32
  • 58