encode.js 838 B

123456789101112131415161718192021222324252627
  1. var forOwn = require('../object/forOwn');
  2. var isArray = require('../lang/isArray');
  3. var forEach = require('../array/forEach');
  4. /**
  5. * Encode object into a query string.
  6. */
  7. function encode(obj){
  8. var query = [],
  9. arrValues, reg;
  10. forOwn(obj, function (val, key) {
  11. if (isArray(val)) {
  12. arrValues = key + '=';
  13. reg = new RegExp('&'+key+'+=$');
  14. forEach(val, function (aValue) {
  15. arrValues += encodeURIComponent(aValue) + '&' + key + '=';
  16. });
  17. query.push(arrValues.replace(reg, ''));
  18. } else {
  19. query.push(key + '=' + encodeURIComponent(val));
  20. }
  21. });
  22. return (query.length) ? '?' + query.join('&') : '';
  23. }
  24. module.exports = encode;