I'm attempting to transform an array of objects into a map, with the index based on a specific attribute value of the object in typescript
4.1.5
Additionally, I am only interested in attributes of a certain type (in this case, string
)
A similar question was posed in javascript
here : Convert object array to hash map, indexed by an attribute value of the Object
type Foo = {
a : string
b : number
}
const foos: Foo[] = []
// should only propose to index by 'a'
const foos_indexed_by_a = indexArrayByKey(foos, 'a')
function indexArrayByKey<T> (array: T[], key: Extract<keyof T, string>): Map<string, T> {
return array.reduce((map, obj) => map.set(obj[key], obj), new Map<string, T>())
}
Currently, I am facing an issue accessing the property key
of obj
(resulting in a compilation error)
Thank you for your assistance :)