Last active
September 2, 2022 09:06
-
-
Save ArtemAvramenko/d92c92ff1b74cbc55be226dcabff90cc to your computer and use it in GitHub Desktop.
TypeScript convert array to dictionary
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
static toDictionary<TItem>( | |
array: TItem[], | |
getKey: (item: TItem) => number): { [id: number]: TItem }; | |
static toDictionary<TItem, TValue>( | |
array: TItem[], | |
getKey: (item: TItem) => number, | |
getValue: (item: TItem) => TValue): { [id: number]: TValue }; | |
static toDictionary<TItem>( | |
array: TItem[], | |
getKey: (item: TItem) => string): { [id: string]: TItem }; | |
static toDictionary<TItem, TValue>( | |
array: TItem[], | |
getKey: (item: TItem) => string, | |
getValue: (item: TItem) => TValue): { [id: string]: TValue }; | |
static toDictionary<TItem>( | |
array: TItem[], | |
getKey: (item: TItem) => number | string, | |
getValue?: (item: TItem) => any): any { // eslint-disable-line @typescript-eslint/no-explicit-any | |
const result = {} as any; // eslint-disable-line @typescript-eslint/no-explicit-any | |
if (array) { | |
if (getValue) { | |
array.forEach(_ => result[getKey(_)] = getValue(_)); | |
} | |
else { | |
array.forEach(_ => result[getKey(_)] = _); | |
} | |
} | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment