0

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?

1
  • 1
    So loop over the keys with every... Commented Jan 28, 2019 at 14:36

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

Comments

0

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);

1 Comment

Unnecessary overcomplication with {}.hasOwnProperty.bind(object), imo.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.