将对象数组转换为由对象键索引的映射
Transform array of objects to a map indexed by object key
我正在尝试将对象数组转换为地图,由 typescript
4.1.5[=18= 中对象的属性值索引]
此外我只想要某种类型的属性(这里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
(编译失败)
感谢您的帮助:)
要过滤具有字符串值的键,您不能使用 Extarct
来过滤字符串(不是数字或符号)的键。您可以使用 KeyOfType
描述
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>())
}
我们使用 T[K]
而不是 string
因为 T[K]
也可以是 string
的子类型所以 TS 会在 string
处抱怨,但对于某些情况这会很好用。
我正在尝试将对象数组转换为地图,由 typescript
4.1.5[=18= 中对象的属性值索引]
此外我只想要某种类型的属性(这里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
(编译失败)
感谢您的帮助:)
要过滤具有字符串值的键,您不能使用 Extarct
来过滤字符串(不是数字或符号)的键。您可以使用 KeyOfType
描述
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>())
}
我们使用 T[K]
而不是 string
因为 T[K]
也可以是 string
的子类型所以 TS 会在 string
处抱怨,但对于某些情况这会很好用。