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"
        }
5
  • Sorry I edited my answer, it needs to be a dynamic loop somehow Commented Feb 6, 2016 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. Commented Feb 6, 2016 at 17:39
  • Ok cool but what if I added other properties in the future. Any way to make it work for unknown keys? Commented Feb 6, 2016 at 17:42
  • function compareKeys(a,b,key){ return a[key] === b[key]; } or something Commented Feb 6, 2016 at 17:42
  • 1
    you can find this two posts helpful. stackoverflow.com/questions/12160998/… stackoverflow.com/questions/20094062/… Commented Feb 6, 2016 at 18:05

2 Answers 2

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

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

1 Comment

Thanks Nina - perfect... :-)
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)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.