user5417542 user5417542 - 3 months ago 11
AngularJS Question

Compare Objects while ignoring some attributes

In my angular application I have 2 objects I want to compare. For that I use angular.equals(obj1, obj2). How ever there are some attributes which don't matter for my comparison and angular.equals() will return false.

What is the best and shortest way to do a comparison in Angular while ignoring some attributes? So for example obj1.name can be "John" and obj2.name can be "Tom" and i will still get true, when all other attributes are the same?

Answer

If there's a set of specific keys you want to compare, you could just loop through those and check if they are the same. Here, I feel generous.

function compareProperties(obj1, obj2, properties) {
  for(var i=0; i<properties.length; ++i) {
    var key = properties[i];
    if(obj1[key] !== obj2[key]) {
      return false;
    }
  }
  return true;
}

var dude = {
  surname: 'Smith',
  name: 'John',
  nickname: 'Dude'
}

var bro = {
  surname: 'Smith',
  name: 'John',
  nickname: 'Bro'
}

compareProperties(dude, bro, ['name','surname']); // returns true
compareProperties(dude, bro, ['name','nickname']); // returns false