queryParams.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. function queryParams(data = {}, isPrefix = true, arrayFormat = 'brackets') {
  2. let prefix = isPrefix ? '?' : ''
  3. let _result = []
  4. if (['indices', 'brackets', 'repeat', 'comma'].indexOf(arrayFormat) == -1) arrayFormat = 'brackets';
  5. for (let key in data) {
  6. let value = data[key]
  7. // 去掉为空的参数
  8. if (['', undefined, null].indexOf(value) >= 0) {
  9. continue;
  10. }
  11. // 如果值为数组,另行处理
  12. if (value.constructor === Array) {
  13. // e.g. {ids: [1, 2, 3]}
  14. switch (arrayFormat) {
  15. case 'indices':
  16. // 结果: ids[0]=1&ids[1]=2&ids[2]=3
  17. for (let i = 0; i < value.length; i++) {
  18. _result.push(key + '[' + i + ']=' + value[i])
  19. }
  20. break;
  21. case 'brackets':
  22. // 结果: ids[]=1&ids[]=2&ids[]=3
  23. value.forEach(_value => {
  24. _result.push(key + '[]=' + _value)
  25. })
  26. break;
  27. case 'repeat':
  28. // 结果: ids=1&ids=2&ids=3
  29. value.forEach(_value => {
  30. _result.push(key + '=' + _value)
  31. })
  32. break;
  33. case 'comma':
  34. // 结果: ids=1,2,3
  35. let commaStr = "";
  36. value.forEach(_value => {
  37. commaStr += (commaStr ? "," : "") + _value;
  38. })
  39. _result.push(key + '=' + commaStr)
  40. break;
  41. default:
  42. value.forEach(_value => {
  43. _result.push(key + '[]=' + _value)
  44. })
  45. }
  46. } else {
  47. _result.push(key + '=' + value)
  48. }
  49. }
  50. return _result.length ? prefix + _result.join('&') : ''
  51. }
  52. export default queryParams