queryString.ts 946 B

1234567891011121314151617181920212223242526272829
  1. /**
  2. * 将对象序列化为URL查询字符串,用于替代第三方的 qs 库,节省宝贵的体积
  3. * 支持基本类型值和数组,不支持嵌套对象
  4. * @param obj 要序列化的对象
  5. * @returns 序列化后的查询字符串
  6. */
  7. export function stringifyQuery(obj: Record<string, any>): string {
  8. if (!obj || typeof obj !== 'object' || Array.isArray(obj))
  9. return ''
  10. return Object.entries(obj)
  11. .filter(([_, value]) => value !== undefined && value !== null)
  12. .map(([key, value]) => {
  13. // 对键进行编码
  14. const encodedKey = encodeURIComponent(key)
  15. // 处理数组类型
  16. if (Array.isArray(value)) {
  17. return value
  18. .filter(item => item !== undefined && item !== null)
  19. .map(item => `${encodedKey}=${encodeURIComponent(item)}`)
  20. .join('&')
  21. }
  22. // 处理基本类型
  23. return `${encodedKey}=${encodeURIComponent(value)}`
  24. })
  25. .join('&')
  26. }