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?

steenbergh
1,7913 gold badges23 silver badges43 bronze badges
asked Jan 28, 2019 at 14:30
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

answered Jan 28, 2019 at 14:33
0
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);

answered Jan 28, 2019 at 14:34
1
  • Unnecessary overcomplication with {}.hasOwnProperty.bind(object), imo. Commented Jan 28, 2019 at 14:36

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.