Source: Core/objectToQuery.js

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