index.ts 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. // @ts-nocheck
  2. // #ifndef UNI-APP-X
  3. type UTSJSONObject = Record<string, any>
  4. // #endif
  5. /**
  6. * 将对象转换为URL查询字符串
  7. * @param data - 需要转换的键值对对象
  8. * @param isPrefix - 是否添加问号前缀,默认为false
  9. * @returns 格式化后的URL查询参数字符串
  10. *
  11. * @example
  12. * // 基础用法
  13. * obj2url({ name: '张三', age: 25 });
  14. * // => "name=%E5%BC%A0%E4%B8%89&age=25"
  15. *
  16. * @example
  17. * // 数组参数处理
  18. * obj2url({ tags: ['js', 'ts'] });
  19. * // => "tags[]=js&tags[]=ts"
  20. *
  21. * @example
  22. * // 包含空值的过滤
  23. * obj2url({ name: '', age: null, city: undefined });
  24. * // => ""
  25. *
  26. * @description
  27. * 1. 自动过滤空值(空字符串、null、undefined)
  28. * 2. 支持数组参数转换(自动添加[]后缀)
  29. * 3. 自动进行URI编码
  30. * 4. 支持自定义是否添加问号前缀
  31. */
  32. export function obj2url(data : UTSJSONObject, isPrefix : boolean = false) : string {
  33. const prefix = isPrefix ? '?' : '';
  34. const _result:string[] = [];
  35. const empty:(any|null)[] = ['', null]
  36. // #ifndef APP-ANDROID
  37. empty.push(undefined)
  38. // #endif
  39. for (const key in data) {
  40. const value = data[key];
  41. // 去掉为空的参数
  42. if (empty.includes(value)) {
  43. continue;
  44. }
  45. if (Array.isArray(value)) {
  46. (value as any[]).forEach((_value) => {
  47. _result.push(
  48. encodeURIComponent(key) + '[]=' + encodeURIComponent(`${_value}`),
  49. );
  50. });
  51. } else {
  52. _result.push(encodeURIComponent(key) + '=' + encodeURIComponent(`${value}`));
  53. }
  54. }
  55. return _result.length > 0 ? prefix + _result.join('&') : '';
  56. }