Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare objects in Angular

Tags:

angularjs

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.

like image 622
selanac82 Avatar asked Dec 05 '13 20:12

selanac82


2 Answers

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
like image 190
klode Avatar answered Oct 17 '22 18:10

klode


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

JSON.stringify(obj1) == JSON.stringify(obj2);
like image 26
tymeJV Avatar answered Oct 17 '22 17:10

tymeJV