I am trying to check if any one of the two given keys are available in a given object
let keys = ['foo', 'bar'];
given object
let obj = {
"foo": "value"
}
let obj1 = {
"key": "value"
}
As we can see in obj foo is present and in obj1 none of the given keys are present.
"key" in obj //can check for single key like this
Need to check anyone of given key should be present in object
You can use Object.keys combined with Array.prototype.includes:
let obj = {
foo: 'value',
key: 'value'
}
let keys = ['foo', 'bar']
// true
console.log(Object.keys(obj).some(k => keys.includes(k)));
keys = ['bar','bar'];
// false
console.log(Object.keys(obj).some(k => keys.includes(k)));
Use Array#some to iterate over the keys list and Object#hasOwnProperty to check if the object has a key:
const hasKeyInList = (obj = {}, keys = []) =>
keys.some(key => obj.hasOwnProperty(key));
const keys = ['foo', 'bar'];
console.log( hasKeyInList({"foo": "value"}, keys) );
console.log( hasKeyInList({"key": "value"}, keys) );