0

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?

user5417542
  • 3,146
  • 6
  • 29
  • 50
  • There is similar question on this link see if it helps http://stackoverflow.com/questions/1068834/object-comparison-in-javascript – Vicky Kumar Aug 25 '16 at 12:00

2 Answers2

1

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
Domino
  • 6,314
  • 1
  • 32
  • 58
  • 1
    Today I learned that "surname" in English is equivalent for "family name" in French, while French "surnom" is "nickname" in English. Good to know. – Domino Aug 25 '16 at 12:09
1

Here's a solution if you only know what attributes you need to skip

var match = true;
var skipAttr = ['attr1', 'attr2', ..., 'attrn'];
var objs = [obj1, obj2];

matchFailed:
for(var i = 0; i < 2; i++) {

  next:
  for(var k in objs[i]) {

    for(var v in skipAttr) {
      if(k == v) 
        break next;
    }

    if(!(k in objs[(i+1)%2]) || (i == 0 && !angular.equals(obj1[k],obj2[k])) ) {
      match = false;
      break matchFailed;
    }
  }
}

console.log(match);
Raghav Tandon
  • 459
  • 5
  • 9
  • I had never seen anyone actively use labeled breaks in JS loops before. I feel like a curious kid poking something with a stick. – Domino Aug 26 '16 at 05:32