objectToQuery.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import defined from "./defined.js";
  2. import DeveloperError from "./DeveloperError.js";
  3. /**
  4. * Converts an object representing a set of name/value pairs into a query string,
  5. * with names and values encoded properly for use in a URL. Values that are arrays
  6. * will produce multiple values with the same name.
  7. * @function objectToQuery
  8. *
  9. * @param {object} obj The object containing data to encode.
  10. * @returns {string} An encoded query string.
  11. *
  12. *
  13. * @example
  14. * const str = Cesium.objectToQuery({
  15. * key1 : 'some value',
  16. * key2 : 'a/b',
  17. * key3 : ['x', 'y']
  18. * });
  19. *
  20. * @see queryToObject
  21. * // str will be:
  22. * // 'key1=some%20value&key2=a%2Fb&key3=x&key3=y'
  23. */
  24. function objectToQuery(obj) {
  25. //>>includeStart('debug', pragmas.debug);
  26. if (!defined(obj)) {
  27. throw new DeveloperError("obj is required.");
  28. }
  29. //>>includeEnd('debug');
  30. let result = "";
  31. for (const propName in obj) {
  32. if (obj.hasOwnProperty(propName)) {
  33. const value = obj[propName];
  34. const part = `${encodeURIComponent(propName)}=`;
  35. if (Array.isArray(value)) {
  36. for (let i = 0, len = value.length; i < len; ++i) {
  37. result += `${part + encodeURIComponent(value[i])}&`;
  38. }
  39. } else {
  40. result += `${part + encodeURIComponent(value)}&`;
  41. }
  42. }
  43. }
  44. // trim last &
  45. result = result.slice(0, -1);
  46. // This function used to replace %20 with + which is more compact and readable.
  47. // However, some servers didn't properly handle + as a space.
  48. // https://github.com/CesiumGS/cesium/issues/2192
  49. return result;
  50. }
  51. export default objectToQuery;