I'm trying to convert an array of object to a map, indexed by an attribue value of the Object in typescript
4.1.5
Furthermore I want only the attributes of a certain type (here string
)
A very similar question have been asked 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>())
}
For now I can't access property key
of obj
(compilation failure)
Thanks for your help :)