30秒学会 JavaScript 片段 · 2023年7月15日

30秒学会 JavaScript 片段 – Assert object keys are valid

Validates all keys in an object match the given keys.

  • Use Object.keys() to get the keys of the given object, obj.
  • Use Array.prototype.every() and Array.prototype.includes() to validate that each key in the object is specified in the keys array.

代码实现

const assertValidKeys = (obj, keys) =>
  Object.keys(obj).every(key => keys.includes(key));

assertValidKeys({ id: 10, name: 'apple' }, ['id', 'name']); // true
assertValidKeys({ id: 10, name: 'apple' }, ['id', 'type']); // false

翻译自:https://www.30secondsofcode.org/js/s/assert-object-key-validity