UNPKG

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