From 1081132477861abe42485dea93e495e0c4460192 Mon Sep 17 00:00:00 2001 From: Chalarangelo Date: Fri, 18 Jun 2021 21:23:58 +0300 Subject: [PATCH] Create indexOn --- snippets/indexOn.md | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 snippets/indexOn.md diff --git a/snippets/indexOn.md b/snippets/indexOn.md new file mode 100644 index 000000000..4bb269156 --- /dev/null +++ b/snippets/indexOn.md @@ -0,0 +1,27 @@ +--- +title: indexOn +tags: array,object,intermediate +firstSeen: 2021-06-27T05:00:00-04:00 +--- + +Creates an object from an array, using the specified key and excluding it from each value. + +- Use `Array.prototype.reduce()` to create an object from `arr`. +- Use object destructuring to get the value of the given `key` and the associated `data` and add the key-value pair to the object. + +```js +const indexOn = (arr, key) => + arr.reduce((obj, v) => { + const { [key]: id, ...data } = v; + obj[id] = data; + return obj; + }, {}); +``` + +```js +indexOn([ + { id: 10, name: 'apple' }, + { id: 20, name: 'orange' } +], x => x.id); +// { '10': { name: 'apple' }, '20': { name: 'orange' } } +```