From 40ef1e41b09fb69b9592a9c3930ae05d6ec77be5 Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Sun, 9 Apr 2023 21:41:58 +0300 Subject: [PATCH] Add 2 new snippets --- snippets/hasValue.md | 22 ++++++++++++++++++++++ snippets/toIdentityObject.md | 20 ++++++++++++++++++++ 2 files changed, 42 insertions(+) create mode 100644 snippets/hasValue.md create mode 100644 snippets/toIdentityObject.md diff --git a/snippets/hasValue.md b/snippets/hasValue.md new file mode 100644 index 000000000..a2c6b4a19 --- /dev/null +++ b/snippets/hasValue.md @@ -0,0 +1,22 @@ +--- +title: Check if object has value +tags: object +author: chalarangelo +cover: plant-corner +firstSeen: 2023-04-10T05:00:00-04:00 +--- + +Checks if the target value exists in a JSON object. + +- Use `Object.values()` to get all the values of the object. +- Use `Array.prototype.includes()` to check if the target value is included in the values array. + +```js +const hasValue = (obj, value) => Object.values(obj).includes(value); +``` + +```js +const obj = { a: 100, b: 200 }; +hasValue(obj, 100); // true +hasValue(obj, 999); // false +``` diff --git a/snippets/toIdentityObject.md b/snippets/toIdentityObject.md new file mode 100644 index 000000000..569ba122b --- /dev/null +++ b/snippets/toIdentityObject.md @@ -0,0 +1,20 @@ +--- +title: Convert array to identity object +tags: array +author: chalarangelo +cover: rain-shopping +firstSeen: 2023-04-16T05:00:00-04:00 +--- + +Converts an array of values into an object with the same values as keys and values. + +- Use `Array.prototype.map()` to map each value to an array of key-value pairs. +- Use `Object.fromEntries()` to convert the array of key-value pairs into an object. + +```js +const toIdentityObject = arr => Object.fromEntries(arr.map(v => [v, v])); +``` + +```js +toIdentityObject(['a', 'b']); // { a: 'a', b: 'b' } +```