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?
-
1So loop over the keys with every...epascarello– epascarello2019年01月28日 14:36:47 +00:00Commented Jan 28, 2019 at 14:36
2 Answers 2
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
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);
-
Unnecessary overcomplication with
{}.hasOwnProperty.bind(object)
, imo.dfsq– dfsq2019年01月28日 14:36:15 +00:00Commented Jan 28, 2019 at 14:36