Skip to content

Instantly share code, notes, and snippets.

@aaronbeall
Created February 15, 2018 21:25
Show Gist options
  • Save aaronbeall/97c6ee9f41da720e2138eb5f90792ff5 to your computer and use it in GitHub Desktop.
Save aaronbeall/97c6ee9f41da720e2138eb5f90792ff5 to your computer and use it in GitHub Desktop.
function arrayToMap<T, K extends keyof T>(array: T[], key: K): { [key: string]: T } {
return array.reduce((map, item) => ({
...map,
[`${item[key]}`]: item
}), {});
}
// Example
const array = [{ id: "a"}, { id: "b" }, { id: "c" }];
const byId = arrayToMap(array, "id"); // { "a": { id: "a"}, "b": { id: "b"}, "c": { id: "c"} }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment