import { get } from "es-toolkit/compat" /** * 把数组按照指定 key 转换为映射表 * [{id:1},{id:2}] => {"1":{id:1}, "2":{id:2}} * * 如果不指定 key 就把元素当成 Key * ["ee","aa","cc"] => {"ee":true, "aa":true, "cc":true} * */ export function arrayToMap( arr: T[], key?: string | ((item: T) => string), options?: { isKeyPath?: boolean } ): { [key: string]: T } { let map: { [key: string]: T } = {} let isKeyFunction = typeof key === "function" for (let item of arr) { if (key) { if (isKeyFunction) { let fKey = (key as any)(item) // @ts-ignore map[fKey] = item } else { if (options?.isKeyPath) { let fKey = get(item, key as string) // @ts-ignore map[fKey] = item } else { // @ts-ignore map[item[key]] = item } } } else { // @ts-ignore map[item] = true } } return map }