Reputation: 31713
I have an array of strings and I want to check if the object has all properties that are in this array.
I could do a for loop and use .hasOwnProperty()
but I want a better and smaller way to do it. I tried things like .includes
, var v in obj
, passing an array to .hasOwnProperty
but nothing seems to work.
const obj = {Password: '123456', Username: 'MeMyselfAndI'}
const checkFields= ['Method', 'Password', 'Username']
return checkIfObjectHaveKeysOfArray(obj, checkFields) // should return false because object doesn't have property 'Method'
Is there a way to do that without using a for loop? If yes, how?
Upvotes: 0
Views: 794
Reputation: 386868
You could use Object.hasOwnProperty
and check every key.
const
object = { Password: '123456', Username: 'MeMyselfAndI' },
checkFields = ['Method', 'Password', 'Username'],
hasAllKeys = checkFields.every({}.hasOwnProperty.bind(object));
console.log(hasAllKeys);
Upvotes: 0
Reputation: 1075755
I could do a for loop and use .hasOwnProperty() but I wan't a better and smaller way to do it
Loops aren't that big. :-) But you could use every
with an arrow function:
return checkFields.every(key => obj.hasOwnProperty(key));
Live Example:
const obj = {Password: '123456', Username: 'MeMyselfAndI'}
const checkFields= ['Method', 'Password', 'Username']
const result = checkFields.every(key => obj.hasOwnProperty(key));
console.log(result); // false
Upvotes: 3