Files
30-seconds-of-code/snippets/assertValidKeys.md
2022-05-14 15:55:07 +03:00

687 B

title, tags, expertise, author, cover, firstSeen
title tags expertise author cover firstSeen
Assert object keys are valid object intermediate chalarangelo blog_images/river-flow.jpg 2021-07-18T05:00:00-04:00

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