UNPKG

830 BPlain TextView Raw
1/**
2 * Normalize an array of object like the following :
3 *
4 * In this example, key = 'id'
5 * [{id:"x", other: "some value"},{id:"y", other: "some value"}]
6 *
7 * TO
8 *
9 * {
10 * x: {id:"x", other: "some value"}
11 * y: {id:"y", other: "some value"}
12 * }
13 * @param {*} arr input array of object to convert
14 * @param {*} key object key to extract
15 */
16import {Index} from './index';
17
18export function normalizeArray<T, K extends keyof T>(arr: Array<T>, key: K): Index<T> {
19 if (!Array.isArray(arr)) throw new Error(`${arr} is not an array`);
20 return arr.reduce((acc, object) => {
21 const keyValue = String(object[key]);
22 return {
23 ...acc,
24 [keyValue]: object,
25 };
26 }, {});
27}
28
29export function denormalize<T>(index: Index<T>): Array<[string, T]> {
30 return Object.keys(index).map(k => [k, index[k]] as [string, T]);
31}
\No newline at end of file