Skip to content Skip to sidebar Skip to footer

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(

Solution 1:

You can use:

var hasAll = Object.keys(obj1).every(function(key) {
  returnObject.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));

Solution 2:

You can write a function to iterate and check:

functionhasAllKeys(requiredObj, secondObj) {
    for (var key in requiredObj) {
        if (!secondObj.hasOwnProperty(key)) {
            returnfalse;
        }
    }

    returntrue;
}

hasAllKeys(SecondObject, FirstObject);

Solution 3:

You can use jQuery's $.map method as follows: $.map(a,function(value, key) {return b[key];}).length != b.length

Post a Comment for "Best Way To Check A Javascript Object Has All The Keys Of Another Javascript Object"