0

I have a few Javascript objects:

var first = {'key' : 1, 'data': 'Hello'};
var second = {'key' : 1, 'data': 'Hello', 'date': '15th'};

I want to write a function which compares the two, checking to see if the key/value pairs in the first object are the same as the second. What's the best way to achieve this?

checkIfObjectContains(first, second);
//This returns true, as all the key/value pairs in the 
//first object are within the second object.

checkIfObjectContains(second, first);
//This returns FALSE, as all the objects in the second object
//are NOT contained in the first.

function checkIfObjectContains(one, two){
    //What goes here?
}
2
  • possible duplicate of Object comparison in JavaScript and several others Commented Sep 9, 2015 at 19:11
  • @Juhana: close, but different. OP needs subset, not just exact equality. Commented Sep 9, 2015 at 19:12

1 Answer 1

2

I do think this a good solution for your problem

function checkIfObjectContains(one, two){
   for (var i in one) {
           if (! two.hasOwnProperty(i) || one[i] !== two[i] ) {
              return false;
           }       
   }
   return true;
}

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

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.