Created
February 15, 2018 21:25
-
-
Save aaronbeall/97c6ee9f41da720e2138eb5f90792ff5 to your computer and use it in GitHub Desktop.
This file contains 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
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