import config from '@/config' interface ConvertArrayToObjectConfig { /** * 待转换对象数组 */ // eslint-disable-next-line @typescript-eslint/no-explicit-any arr: any[] | undefined | null /** * 待搜索的元素key值,可以是数组,若使用数组则使用 || 规则 */ key: string | string[] /** * 是否返回对象所有数据,若为true则containsKeys值被忽略 */ whole?: boolean /** * 返回对象中指定key */ containsKeys?: string | string[] } /** * 根据数组返回由key组成的键值对形式的对象 * * @param config 配置项 * * @example convertArrayToObject({[{a:1, b:2}, {a:2,b:3}], 'a', false, ['b']}) => {'1':{b:2}, '2':{b:3} } * @example convertArrayToObject({[{a:1, b:2}, {a:2,b:3}], 'a', false, 'b'}) => {'1':2, '2':3 } * @example convertArrayToObject({[{a:1, b:2}, {a:2,b:3}], 'a'}) => {'1':{ a:1,b:2 }, '2':{a:2,b:3} } * * @returns 由原对象数组使用传入的key对应的value值作为新对象的key值组成的对象 * */ export function convertArrayToObject(c: ConvertArrayToObjectConfig): R { const { arr, key, whole, containsKeys } = Object.assign({ whole: false, containsKeys: '' }, c) if (Array.isArray(arr) && Object.keys(arr).length > 0) { return arr.reduce((a, needle) => { const kIndex = searchIndexByKey(key, needle) if (kIndex) { let value = {} if (!whole || !!containsKeys) { if (Array.isArray(containsKeys)) { containsKeys.forEach((ckey) => { value[ckey] = needle[ckey] }) } else if (containsKeys) { value = needle[containsKeys] } } else { value = needle } a[kIndex] = value } return a }, {}) } // eslint-disable-next-line @typescript-eslint/no-explicit-any return {} as any } /** * 根据key值从待搜索对象中查找值 * * @param key 从待查询对象中提取得key值,若使用数组则使用 || 规则进行赋值 * @param needle 待查询对象 * @returns 搜索到的值,可能为空 */ function searchIndexByKey(key: string | string[], needle) { let index = '' if (Array.isArray(key)) { index = key.reduce((res, k) => { return needle[k] || res }, index) } else { index = needle[key] } return index } /** * 获取下载文件地址 * @param code 附件code */ export function getDownloadURL(code: string) { return `${config.apiURL}/api/file/download?code=${code}` }