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?
}
holl
  • 318
  • 3
  • 12
  • possible duplicate of [Object comparison in JavaScript](http://stackoverflow.com/questions/1068834/object-comparison-in-javascript) and several others – JJJ Sep 09 '15 at 19:11
  • @Juhana: close, but different. OP needs subset, not just exact equality. – Linuxios Sep 09 '15 at 19:12

1 Answers1

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;
}
mariodiniz
  • 102
  • 5