Compare objects in Angular

Angularjs

Angularjs Problem Overview


Is it possible to do a "deep" comparison of two object in Angular? What I would like to do is compare each key/value pair. For example:

Object 1

{
   key1: "value1",
   key2: "value2",
   key3: "value3"
}

Object 2

{
   key1: "value1",
   key2: "newvalue",
   key3: "value3" 
}

What I need is for the comparison to fail since only one of the key/value pairs is diffent. In other words ALL of the key/value pairs must match exactly or else failure. Is this something already built into Angular. I'm sure I could write my own service if I really needed to, but I was hoping it was already built in. Similar to angular.equals.

Angularjs Solutions


Solution 1 - Angularjs

To compare two objects you can use:

angular.equals(obj1, obj2)

It does a deep comparison and does not depend on the order of the keys See AngularJS DOCS and a little Demo

var obj1 = {
  key1: "value1",
  key2: "value2",
  key3: {a: "aa", b: "bb"}
}

var obj2 = {
  key2: "value2",
  key1: "value1",
  key3: {a: "aa", b: "bb"}
}

angular.equals(obj1, obj2) //<--- would return true

Solution 2 - Angularjs

Assuming that the order is the same in both objects, just stringify them both and compare!

JSON.stringify(obj1) == JSON.stringify(obj2);

Solution 3 - Angularjs

Bit late on this thread. angular.equals does deep check, however does anyone know that why its behave differently if one of the member contain "$" in prefix ?

You can try this [Demo](http://plnkr.co/edit/Dv3xseVGK0B3rDRksnUM?p=preview "") with following input

var obj3 = {}
obj3.a=  "b";
obj3.b={};
obj3.b.$c =true;

var obj4 = {}
obj4.a=  "b";
obj4.b={};
obj4.b.$c =true;

angular.equals(obj3,obj4);

Solution 4 - Angularjs

I know it's kinda late answer but I just lost about half an hour debugging cause of this, It might save someone some time.

BE MINDFUL, If you use angular.equals() on objects that have property obj.$something (property name starts with $) those properties will get ignored in comparison.

Example:

var obj1 = {
  $key0: "A",
  key1: "value1",
  key2: "value2",
  key3: {a: "aa", b: "bb"}
}

var obj2 = {
  $key0: "B"
  key2: "value2",
  key1: "value1",
  key3: {a: "aa", b: "bb"}
}

angular.equals(obj1, obj2) //<--- would return TRUE (despite it's not true)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionselanac82View Question on Stackoverflow
Solution 1 - AngularjsklodeView Answer on Stackoverflow
Solution 2 - AngularjstymeJVView Answer on Stackoverflow
Solution 3 - AngularjsKM.View Answer on Stackoverflow
Solution 4 - AngularjsDanteTheSmithView Answer on Stackoverflow