find-name-by-list-code.ts 923 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import XEUtils from "xe-utils";
  2. interface Option {
  3. // 数组中的 code
  4. listCode: string,
  5. // 数组中的 name
  6. listValue: string
  7. }
  8. const defaultValue: Option = {
  9. listCode: 'code',
  10. listValue: 'name'
  11. }
  12. /**
  13. *
  14. * @param arr 数组
  15. * @param code 需要寻找的值
  16. * @param option 配置
  17. * @return str {string} name
  18. */
  19. const findValueByListCode = (arr: any[] | object, code: string | number, option: Option = defaultValue): string => {
  20. const {listCode, listValue} = option
  21. if (XEUtils.isEmpty(arr)) {
  22. return '';
  23. }
  24. if (!XEUtils.isArray(arr)) {
  25. return '';
  26. }
  27. if (typeof code === 'undefined' || code === null) {
  28. return '';
  29. }
  30. for (let i: number = 0, len: number = arr.length; i < len; i++) {
  31. if (arr[i][listCode] === code) {
  32. return arr[i][listValue];
  33. }
  34. }
  35. return ''
  36. }
  37. export default findValueByListCode;