From f5410f122b491897ade6adc40799c04eca898239 Mon Sep 17 00:00:00 2001 From: Chalarangelo Date: Fri, 18 Jun 2021 21:35:44 +0300 Subject: [PATCH] Add assertValidKeys --- snippets/assertValidKeys.md | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 snippets/assertValidKeys.md diff --git a/snippets/assertValidKeys.md b/snippets/assertValidKeys.md new file mode 100644 index 000000000..290c817f4 --- /dev/null +++ b/snippets/assertValidKeys.md @@ -0,0 +1,20 @@ +--- +title: assertValidKeys +tags: object,intermediate +firstSeen: 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. + +```js +const assertValidKeys = (obj, keys) => + Object.keys(obj).every(key => keys.includes(key)); +``` + +```js +assertValidKeys({ id: 10, name: 'apple' }, ['id', 'name']); // true +assertValidKeys({ id: 10, name: 'apple' }, ['id', 'type']); // false +```