import { get, isArray, isFunction, isObject, isString, isUndefined } from 'lodash-es'; export function useParams() { function getParams( data: object, dynamicParams?: string | Array | object, defaultParams?: object, ): any { let paramsObject = {}; if (isString(dynamicParams)) { paramsObject = getParamsString(data, dynamicParams); } else if (isArray(dynamicParams)) { paramsObject = getParamsArray(data, dynamicParams); } else if (isFunction(dynamicParams)) { paramsObject = getParamsFunction(data, dynamicParams); } else if (isObject(dynamicParams)) { // Function is Object paramsObject = getParamsObject(data, dynamicParams); } return { ...defaultParams, ...paramsObject }; } function getParamsString(data: object, dynamicParams: string, key?: string): object { if (dynamicParams.endsWith('[]')) { dynamicParams = dynamicParams.split('[]')[0]; if ((data as any).list) { return { [key || dynamicParams]: (data as any).list.map((record: any) => { return record[dynamicParams]; }), }; } else { return { [key || dynamicParams]: [get(data, dynamicParams)] }; //支持单条数据数组形式 } } if (dynamicParams.includes('[].')) { const dp = dynamicParams.split('[].'); const list = getParamsString(data, dp[0])[dp[0]]; if (isArray(list)) { const rd = list.reduce((prev, cur) => { const _data = get(cur, dp[1]); if (!isUndefined(_data)) { prev.push(_data); } return prev; }, []); // console.log("rd.join(',')", { [key || dynamicParams]: rd.join(',') }); return { [key || dynamicParams]: rd.join(',') }; //支持单条数据数组形式 } } const value = get(data, dynamicParams); if (!isUndefined(value)) { return { [key || dynamicParams]: get(data, dynamicParams) }; } return {}; } function getParamsArray(data: object, dynamicParams: Array): object { return dynamicParams.reduce((prev, cur) => { return Object.assign(prev, getParamsString(data, cur)); }, {}); } function getParamsObject(data: object, dynamicParams: any): object { return Object.keys(dynamicParams).reduce((prev, cur) => { return Object.assign(prev, getParamsString(data, dynamicParams[cur], cur)); }, {}); } function getParamsFunction(data: object, dynamicParams: Function): object { return dynamicParams(data); } function hasArrayParams(dynamicParams: Record): boolean { return Object.keys(dynamicParams).some((key) => { return dynamicParams[key].endsWith('[]'); }); } return { getParams, hasArrayParams }; }