holl
holl

Reputation: 308

Checking if a Javascript object contains the same key/value pairs as another

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?
}

Upvotes: 0

Views: 4005

Answers (1)

mariodiniz
mariodiniz

Reputation: 102

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

Upvotes: 2

Related Questions