【发布时间】:2022-01-20 21:21:00
【问题描述】:
我正在尝试将对象数组转换为地图,由typescript中的对象属性值索引4.1.5
此外,我只想要某种类型的属性(这里是string)
javascript 在这里提出了一个非常相似的问题: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>())
}
目前我无法访问obj 的属性key(编译失败)
感谢您的帮助:)
【问题讨论】:
标签: arrays typescript hashmap