Reputation: 7421
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 : '...'
}
Upvotes: 2
Views: 2177
Reputation: 1
Another way to do this, that seems to work fine as well.
const o1 = {
a : '....',
b : '...',
c : '...',
d : '...'
},
o2 = {
b : '...',
d : '...',
};
///////////////////////
///// I. IN ONE LINE
///////////////////////
/**/
/**/ if(Object.keys(o2).every(key =>
/**/ key in o1
/**/ // Object.keys(o1).includes(key)
/**/ // Object.keys(o1).filter(x => x==key).length
/**/ ))
/**/ console.log(true);
/**/ else throw new Error("...");
/**/
///////////////////////
///////////////////////
///// II. IN A FUNCTION
///////////////////////
/**/
/**/ var hasAll = (o1 , o2) => {
/**/ let r = Object.keys(o2).every(key =>
/**/ // Object.keys(o1).includes(key)
/**/ // key in o1
/**/ // Object.keys(o1).filter(x => x==key).length
/**/
/**/ Object.keys(o1)
/**/ .reduce((acc,act,arr) =>
/**/ acc && (key in o1) // , true
/**/ )
/**/
/**/ );
/**/ return r;
/**/ }
/**/
/**/ let cond = hasAll(o1 , o2);
/**/
/**/ console.log(cond);
/**/
/**/ if (cond) console.log(true)
// /**/ else throw new Error("At least, one key doesn'e exist");
/**/
/**/ ////////
/**/
/**/ cond = hasAll(o2 , o1);
/**/
/**/ console.log(cond);
/**/
/**/ if (cond) console.log(true)
/**/ else throw new Error("At least, one key doesn'e exist");
/**/
///////////////////////
Upvotes: -1
Reputation: 110
You can use jQuery's $.map
method as follows:
$.map(a,function(value, key) {return b[key];}).length != b.length
Upvotes: 1
Reputation: 47099
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));
Upvotes: 5
Reputation: 104775
You can write a function to iterate and check:
function hasAllKeys(requiredObj, secondObj) {
for (var key in requiredObj) {
if (!secondObj.hasOwnProperty(key)) {
return false;
}
}
return true;
}
hasAllKeys(SecondObject, FirstObject);
Upvotes: 5