Best way to Check a JavaScript Object has all the keys of another JavaScript Object

I have two JS objects, I want to check if the first Object has all the second Object’s keys and do something, otherwise, throw an exception. What’s the best way to do it?

function(obj1, obj2){
    if(obj1.HasAllKeys(obj2)) {
         //do something
    }
    else{
         throw new Error(...);
    } 
};

For example in below example since FirstObject has all the SecondObject’s key it should run the code :

FirstObject
{
    a : '....',
    b : '...',
    c : '...',
    d : '...'
}
SecondObject
{    
    b : '...',    
    d : '...'
}

But in below example I want to throw an exception since XXX doesnt exist in FirstObject:

FirstObject
{
    a : '....',
    b : '...',
    c : '...',
    d : '...'
}
SecondObject
{    
    b : '...',    
    XXX : '...'
}

Answer

You can use:

var hasAll = Object.keys(obj1).every(function(key) {
  return Object.prototype.hasOwnProperty.call(obj2, key);
});
console.log(hasAll); // true if obj2 has all - but maybe more - keys that obj1 have.

As a “one-liner”:

var hasAll = Object.keys(obj1).every(Object.prototype.hasOwnProperty.bind(obj2));