简体   繁体   English

如何检查对象是否具有数组中的键?

[英]How to check if an object has keys that are in an array?

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. 我可以做一个for循环并使用.hasOwnProperty()但是我想要一种更好,更小的方法。 I tried things like .includes , var v in obj , passing an array to .hasOwnProperty but nothing seems to work. 我尝试了诸如.includesvar v in obj类的事情,将数组传递给.hasOwnProperty但似乎没有任何效果。

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? 有没有一种方法,而无需使用for循环? If yes, how? 如果是,怎么办?

I could do a for loop and use .hasOwnProperty() but I wan't a better and smaller way to do it 我可以做一个for循环并使用.hasOwnProperty()但我没有更好,更小的方法

Loops aren't that big. 循环不是那么大。 :-) But you could use every with an arrow function: :-)但是您可以将every箭头功能使用:

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. 您可以使用Object.hasOwnProperty并检查每个键。

 const object = { Password: '123456', Username: 'MeMyselfAndI' }, checkFields = ['Method', 'Password', 'Username'], hasAllKeys = checkFields.every({}.hasOwnProperty.bind(object)); console.log(hasAllKeys); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM