Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 : '...'
}
like image 869
Am1rr3zA Avatar asked Dec 20 '25 16:12

Am1rr3zA


1 Answers

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));
like image 118
Andreas Louv Avatar answered Dec 22 '25 07:12

Andreas Louv



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!