url.params.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. /**
  2. * 对象转换为url参数形式
  3. * @param {Object} param 将要转换为URL参数的字符串对象
  4. * @param {String} key URL 参数字符串的前缀
  5. * @param {Boolean} encode 是否进行URL编码,默认为true
  6. * @return {String} URL参数字符串
  7. */
  8. export function jsonToUrlParams(param, key, encode) {
  9. if (param == null) return '';
  10. let paramStr = '';
  11. let t = typeof(param);
  12. if (t == 'string' || t == 'number' || t == 'boolean') {
  13. paramStr += '&' + key + '=' + ((encode == null || encode) ? encodeURIComponent(param) : param);
  14. } else {
  15. for (var i in param) {
  16. var k = key == null ? i : key + (param instanceof Array ? '[' + i + ']' : '.' + i);
  17. paramStr += jsonToUrlParams(param[i], k, encode);
  18. }
  19. }
  20. return paramStr;
  21. }
  22. /**
  23. * @param {Array} actual
  24. * @returns {Array}
  25. */
  26. export function cleanArray(actual) {
  27. const newArray = []
  28. for (let i = 0; i < actual.length; i++) {
  29. if (actual[i]) {
  30. newArray.push(actual[i])
  31. }
  32. }
  33. return newArray
  34. }
  35. /**
  36. * json对象转Url参数2
  37. * @param {Object} json
  38. * @returns {Array}
  39. */
  40. export function jsonToUrlParams2(json) {
  41. if (!json) return ''
  42. return cleanArray(
  43. Object.keys(json).map(key => {
  44. if (json[key] === undefined) return ''
  45. return encodeURIComponent(key) + '=' + encodeURIComponent(json[key])
  46. })
  47. ).join('&')
  48. }