queryParams.js 1.6 KB

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