objectToQuery.js 1.9 KB

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