UNPKG

1.02 kBJavaScriptView Raw
1/**
2 * Copyright (c) 2015-present, Facebook, Inc.
3 *
4 * This source code is licensed under the MIT license found in the
5 * LICENSE file in the root directory of this source tree.
6 *
7 * strict
8 */
9
10/**
11 * Creates a keyed JS object from an array, given a function to produce the keys
12 * for each value in the array.
13 *
14 * This provides a convenient lookup for the array items if the key function
15 * produces unique results.
16 *
17 * const phoneBook = [
18 * { name: 'Jon', num: '555-1234' },
19 * { name: 'Jenny', num: '867-5309' }
20 * ]
21 *
22 * // { Jon: { name: 'Jon', num: '555-1234' },
23 * // Jenny: { name: 'Jenny', num: '867-5309' } }
24 * const entriesByName = keyMap(
25 * phoneBook,
26 * entry => entry.name
27 * )
28 *
29 * // { name: 'Jenny', num: '857-6309' }
30 * const jennyEntry = entriesByName['Jenny']
31 *
32 */
33export default function keyMap(list, keyFn) {
34 return list.reduce(function (map, item) {
35 return map[keyFn(item)] = item, map;
36 }, Object.create(null));
37}
\No newline at end of file