UNPKG

646 BJavaScriptView Raw
1/**
2 * Creates a keyed JS object from an array, given a function to produce the keys
3 * and a function to produce the values from each item in the array.
4 *
5 * const phoneBook = [
6 * { name: 'Jon', num: '555-1234' },
7 * { name: 'Jenny', num: '867-5309' }
8 * ]
9 *
10 * // { Jon: '555-1234', Jenny: '867-5309' }
11 * const phonesByName = keyValMap(
12 * phoneBook,
13 * entry => entry.name,
14 * entry => entry.num
15 * )
16 *
17 */
18export default function keyValMap(list, keyFn, valFn) {
19 return list.reduce(function (map, item) {
20 map[keyFn(item)] = valFn(item);
21 return map;
22 }, Object.create(null));
23}