export function transformSomeToArray(source: any) { if (typeof source === 'string') return source.split(','); if (typeof source === 'object') { if (source instanceof Array) return source; else { const arr = []; for (const key in source) arr.push(source[key]); return arr; } } return source; } export interface FindAPropCondition { /** * 匹配类型 * startWith: (需要name)匹配以指定字符串开头的属性值 * endWith: (需要name)匹配以指定字符串结尾的属性值 * contain: (需要name)匹配包含指定字符串的属性值 * match: (需要name)匹配完全等于指定字符串的属性值 * selectOnlyOne: 如果只有一个key,仅返回此key的属性值 * selectAtLestOne: 如果没有匹配到任何属性值,返回keys中第一个 */ type: 'startWith'|'endWith'|'contain'|'match'|'selectOnlyOne'|'selectAtLestOne'; name?: string; } export function findAProp(source: Record, matchConditions: FindAPropCondition[]) { // 获取source对象的所有键 const keys = Object.keys(source); if (matchConditions.some(cond => cond.type === 'selectOnlyOne')) { // 如果只有一个key,仅返回此key的属性值 if (keys.length === 1) return source[keys[0]]; } // 遍历所有匹配条件 for (const condition of matchConditions) { switch (condition.type) { case 'startWith': if (condition.name) { // 查找以指定字符串开头的属性值 for (const key of keys) { if (key.startsWith(condition.name)) { return source[key]; } } } break; case 'endWith': if (condition.name) { // 查找以指定字符串开头的属性值 for (const key of keys) { if (key.endsWith(condition.name)) { return source[key]; } } } break; case 'match': if (condition.name) { // 查找完全等于指定字符串的属性值 for (const key of keys) { if (key === condition.name) { return source[key]; } } } break; case 'contain': if (condition.name) { // 查找包含指定字符串的属性值 for (const key of keys) { if (key.includes(condition.name)) { return source[key]; } } } break; } } if (matchConditions.some(cond => cond.type === 'selectAtLestOne')) { // 如果没有匹配到任何属性值,返回keys中第一个 if (keys.length > 0) { return source[keys[0]]; } } // 如果所有条件都未匹配到,返回undefined return undefined; }