Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save ciel/ded08633c4db26070a9dd74aa32e121d to your computer and use it in GitHub Desktop.

Select an option

Save ciel/ded08633c4db26070a9dd74aa32e121d to your computer and use it in GitHub Desktop.
TypeScript convert array to dictionary
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