Utils.ts 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. export function transformSomeToArray(source: any) {
  2. if (typeof source === 'string')
  3. return source.split(',');
  4. if (typeof source === 'object') {
  5. if (source instanceof Array)
  6. return source;
  7. else {
  8. const arr = [];
  9. for (const key in source)
  10. arr.push(source[key]);
  11. return arr;
  12. }
  13. }
  14. return source;
  15. }
  16. export interface FindAPropCondition {
  17. /**
  18. * 匹配类型
  19. * startWith: (需要name)匹配以指定字符串开头的属性值
  20. * endWith: (需要name)匹配以指定字符串结尾的属性值
  21. * contain: (需要name)匹配包含指定字符串的属性值
  22. * match: (需要name)匹配完全等于指定字符串的属性值
  23. * selectOnlyOne: 如果只有一个key,仅返回此key的属性值
  24. * selectAtLestOne: 如果没有匹配到任何属性值,返回keys中第一个
  25. */
  26. type: 'startWith'|'endWith'|'contain'|'match'|'selectOnlyOne'|'selectAtLestOne';
  27. name?: string;
  28. }
  29. export function findAProp(source: Record<string, any>, matchConditions: FindAPropCondition[]) {
  30. // 获取source对象的所有键
  31. const keys = Object.keys(source);
  32. if (matchConditions.some(cond => cond.type === 'selectOnlyOne')) {
  33. // 如果只有一个key,仅返回此key的属性值
  34. if (keys.length === 1)
  35. return source[keys[0]];
  36. }
  37. // 遍历所有匹配条件
  38. for (const condition of matchConditions) {
  39. switch (condition.type) {
  40. case 'startWith':
  41. if (condition.name) {
  42. // 查找以指定字符串开头的属性值
  43. for (const key of keys) {
  44. if (key.startsWith(condition.name)) {
  45. return source[key];
  46. }
  47. }
  48. }
  49. break;
  50. case 'endWith':
  51. if (condition.name) {
  52. // 查找以指定字符串开头的属性值
  53. for (const key of keys) {
  54. if (key.endsWith(condition.name)) {
  55. return source[key];
  56. }
  57. }
  58. }
  59. break;
  60. case 'match':
  61. if (condition.name) {
  62. // 查找完全等于指定字符串的属性值
  63. for (const key of keys) {
  64. if (key === condition.name) {
  65. return source[key];
  66. }
  67. }
  68. }
  69. break;
  70. case 'contain':
  71. if (condition.name) {
  72. // 查找包含指定字符串的属性值
  73. for (const key of keys) {
  74. if (key.includes(condition.name)) {
  75. return source[key];
  76. }
  77. }
  78. }
  79. break;
  80. }
  81. }
  82. if (matchConditions.some(cond => cond.type === 'selectAtLestOne')) {
  83. // 如果没有匹配到任何属性值,返回keys中第一个
  84. if (keys.length > 0) {
  85. return source[keys[0]];
  86. }
  87. }
  88. // 如果所有条件都未匹配到,返回undefined
  89. return undefined;
  90. }