Forked from ArtemAvramenko/convert_array_to_dictionary.ts
Created
December 30, 2017 05:18
-
-
Save ciel/ded08633c4db26070a9dd74aa32e121d 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 { | |
| var result = <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