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?

4
  • do you like to compare the value of the same key? why angular? Commented Sep 8, 2016 at 7:28
  • possible duplicate: stackoverflow.com/questions/29133885/… Commented Sep 8, 2016 at 7:28
  • i am already working on angular js, obj1 is coming from database and obj2 is user input i want to check difference field by field Commented Sep 8, 2016 at 7:34
  • It's not duplicate this answer is for array i want to compare objects. Commented Sep 8, 2016 at 7:37

3 Answers 3

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..

Sign up to request clarification or add additional context in comments.

Comments

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'));

Comments

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;
            }
        }
    })
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.