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 :)
CodePudding user response:
To filter the keys based on which have a string value you can't use Extarct that filters the keys which are strings (not number or symbol). You can use KeyOfType described here
type KeyOfType<T, V> = keyof {
[P in keyof T as T[P] extends V? P: never]: any
}
function indexArrayByKey<T, K extends KeyOfType<T, string>> (array: T[], key: K): Map<T[K], T> {
return array.reduce((map, obj) => map.set(obj[key], obj), new Map<T[K], T>())
}
We use T[K] instead of string because T[K] could also be a subtype of string so TS would complain at string, but for cases this will work well.
