UNPKG

824 BJavaScriptView Raw
1/**
2 * Creates a keyed JS object from an array, given a function to produce the keys
3 * for each value in the array.
4 *
5 * This provides a convenient lookup for the array items if the key function
6 * produces unique results.
7 *
8 * const phoneBook = [
9 * { name: 'Jon', num: '555-1234' },
10 * { name: 'Jenny', num: '867-5309' }
11 * ]
12 *
13 * // { Jon: { name: 'Jon', num: '555-1234' },
14 * // Jenny: { name: 'Jenny', num: '867-5309' } }
15 * const entriesByName = keyMap(
16 * phoneBook,
17 * entry => entry.name
18 * )
19 *
20 * // { name: 'Jenny', num: '857-6309' }
21 * const jennyEntry = entriesByName['Jenny']
22 *
23 */
24export default function keyMap(list, keyFn) {
25 return list.reduce(function (map, item) {
26 map[keyFn(item)] = item;
27 return map;
28 }, Object.create(null));
29}