1

If I have the following two objects (Object A and Object B), how can I check if Object B's key/value exists with Object A? In the below example it should return True because both 'make: "Apple"' and 'Model: "iPad"' exists in Object A.

Edit: Object B will be dynamic and may contain only Make or only Model. More keys are added dynamically via checkbox filters.

Is it easier to use a library such as Underscore? If so what functions would be applicable?

I hope this makes sense?

        var a = {
            Make: "Apple",
            Model: "iPad",
            hasScreen: "yes",
            Review: "Great product!",
        }

        var b = {
            Make: "Apple",
            Model: "iPad"
        }
curv
  • 3,796
  • 4
  • 33
  • 48
  • Sorry I edited my answer, it needs to be a dynamic loop somehow – curv Feb 06 '16 at 17:38
  • in the case of your edit, `b.Make` would just be undefined and the comparison would just return false. `a.Make === b.Make` still makes sense. – Gustav Feb 06 '16 at 17:39
  • Ok cool but what if I added other properties in the future. Any way to make it work for unknown keys? – curv Feb 06 '16 at 17:42
  • `function compareKeys(a,b,key){ return a[key] === b[key]; }` or something – Joseph Young Feb 06 '16 at 17:42
  • 1
    you can find this two posts helpful. http://stackoverflow.com/questions/12160998/compare-two-json-arrays-in-jquery-or-javascript http://stackoverflow.com/questions/20094062/jquery-comparing-and-find-out-the-difference-between-2-json-array – Enrico Acampora Feb 06 '16 at 18:05

2 Answers2

3

Just iterate over all keys and check if the values are equal.

var a = { Make: "Apple", Model: "iPad", hasScreen: "yes", Review: "Great product!" },
    b = { Make: "Apple", Model: "iPad" },
    every = Object.keys(b).every(function (k) {
        return a[k] === b[k];
    });

document.write(every);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
2

There’s no builtin way of doing this, but you can use your own implementation (see Nina Scholz’ answer) or Lodash’s _.isMatch function (or Underscore’s _.isMatch):

_.isMatch(a, b)
Iso
  • 3,148
  • 23
  • 31