Javascript 按键的Typescript组数组
如何键入reduce函数参数Javascript 按键的Typescript组数组,javascript,typescript,Javascript,Typescript,如何键入reduce函数参数 interface IGroupArrayByKey<T> { data: T[] key: string } export const groupArrayByKey = <T>({ data, key }: IGroupArrayByKey<T>): object => { return data.reduce((acc: any, item: any) => { retu
interface IGroupArrayByKey<T> {
data: T[]
key: string
}
export const groupArrayByKey = <T>({ data, key }: IGroupArrayByKey<T>): object => {
return data.reduce((acc: any, item: any) => {
return { ...acc, [item[key]]: [...(acc[item[key]] || []), item] }
}, {})
}
接口IGroupArrayByKey{
数据:T[]
关键字:字符串
}
export const groupArrayByKey=({data,key}:IGroupArrayByKey):object=>{
返回数据。减少((会计科目:任何,项目:任何)=>{
返回{…acc[item[key]]:[…(acc[item[key]]| |[]),item]}
}, {})
}
groupArrayByKey
函数的工作原理是将数组作为date
和key
进行分组两个注意事项:
keyof T
列出了T类型的所有属性,不允许传递不是该对象键的任意字符串。非常有用项[keyProp]
是字符串,但对象中的索引器只能是字符串或数字。这就是为什么这个丑陋的像字符串一样未知的原因。如果您使用的是地图
,那么我们就不需要演员阵容
接口IGroupArrayByKey{
数据:T[]
keyProp:KEYOFT
}
export const groupArrayByKey=({data,keyProp}:IGroupArrayByKey)=>{
返回数据。减少((会计科目,项目)=>{
const key=项[keyProp]与字符串一样未知;
返回{…acc[key]:[…(acc[key]| |[]),item]}
}, {})
}
interface IGroupArrayByKey<T> {
data: T[]
keyProp: keyof T
}
export const groupArrayByKey = <T>({ data, keyProp }: IGroupArrayByKey<T>) => {
return data.reduce<{ [key: string]: T[] }>((acc, item) => {
const key = item[keyProp] as unknown as string;
return { ...acc, [key]: [...(acc[key] || []), item] }
}, {})
}