Compare objects in Angular

Is it possible to perform a β€œdeep” comparison of two objects 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" } 

I need the comparison to fail, since only one of the key / value pairs has a different nature. In other words, all key / value pairs must match exactly or fail. This is already something already built into Angular. I am sure that I could write my own service if I really need it, but I was hoping it was already built in. Like Angular.equals.

+67
angularjs
Dec 05 '13 at 20:13
source share
4 answers

To compare two objects you can use:

angular.equals(obj1, obj2)

This makes 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 
+183
Dec 05 '13 at 21:13
source share

Assuming the order is the same for both objects, just stringify both of them and compare!

 JSON.stringify(obj1) == JSON.stringify(obj2); 
+18
Dec 05 '13 at 20:16
source share

Bit late in this thread. angular.equals does a deep check, however does anyone know why it behaves differently if one of the members contains "$" in the prefix?

You can try this demo with the following entry

 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); 
+4
Mar 04 '15 at 6:12
source share

I know this is somehow a late answer, but I just lost about half an hour debugging this reason, it can save someone.

BE MINDFUL, if you use angular.equals() for objects with the obj.$something angular.equals() property (property name starts with $) , these properties will be 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 not true) 
0
Dec 12 '17 at 12:15
source share



All Articles