2

I have two javascript Object

    var obj1= {
           key1:'value1',
           key2:'value2'
    };

And

 var obj2= {
           key1:'value1',
           key2:'someOtherValue'
    };

As you can see there is one difference b/w both objects at key2, i want a angular foreach loop which can check both objects and can return a console message "Difference is at key2". I already tried angular foreach but it doesn't allow more than one object so how should i compare?

Arpit Kumar
  • 2,179
  • 5
  • 28
  • 53

3 Answers3

0

Please dont use angular.foreach.

  • Javascript for is faster.
  • you wont be able to use break in angular.foreach.

var diffs = [];
for (var key in obj1) {
   if obj1[key] !== obj2[key]{
     diffs.append([key]);
   }
}
console.log(diffs)

Assuming both dictionaries have same keys..

SuperNova
  • 25,512
  • 7
  • 93
  • 64
0

In plain Javascript, you could use a Map for it.

var obj1 = { key1: 'value1', key2: 'value2' },
    obj2 = { key1: 'value1', key2: 'someOtherValue' },
    map = new Map();

Object.keys(obj1).forEach(k => map.set(k, obj1[k]));
Object.keys(obj2).forEach(k => map.get(k) !== obj2[k] && console.log(k + ' is different'));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

Here is pure angularjs code with angular foreach loop.

var keepGoing = true;
angular.forEach(obj1, function(value, key){
    angular.forEach(obj2, function(value2, key2){
        if(keepGoing) {
            if(value == value2){
                keepGoing = true;
            }
            else{
                console.log('Difference is at', key2)
                keepGoing = false;
            }
        }
    })
})
Amruth
  • 5,792
  • 2
  • 28
  • 41