Blame view

uview-ui/libs/function/queryParams.js 1.49 KB
290144e9   易尊强   第一次
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
  /**
   * 对象转url参数
   * @param {*} data,对象
   * @param {*} isPrefix,是否自动加上"?"
   */
  function queryParams(data = {}, isPrefix = true, arrayFormat = 'brackets') {
  	let prefix = isPrefix ? '?' : ''
  	let _result = []
  	if (['indices', 'brackets', 'repeat', 'comma'].indexOf(arrayFormat) == -1) arrayFormat = 'brackets';
  	for (let key in data) {
  		let value = data[key]
  		// 去掉为空的参数
  		if (['', undefined, null].indexOf(value) >= 0) {
  			continue;
  		}
  		// 如果值为数组,另行处理
  		if (value.constructor === Array) {
  			// e.g. {ids: [1, 2, 3]}
  			switch (arrayFormat) {
  				case 'indices':
  					// 结果: ids[0]=1&ids[1]=2&ids[2]=3
  					for (let i = 0; i < value.length; i++) {
  						_result.push(key + '[' + i + ']=' + value[i])
  					}
  					break;
  				case 'brackets':
  					// 结果: ids[]=1&ids[]=2&ids[]=3
  					value.forEach(_value => {
  						_result.push(key + '[]=' + _value)
  					})
  					break;
  				case 'repeat':
  					// 结果: ids=1&ids=2&ids=3
  					value.forEach(_value => {
  						_result.push(key + '=' + _value)
  					})
  					break;
  				case 'comma':
  					// 结果: ids=1,2,3
  					let commaStr = "";
  					value.forEach(_value => {
  						commaStr += (commaStr ? "," : "") + _value;
  					})
  					_result.push(key + '=' + commaStr)
  					break;
  				default:
  					value.forEach(_value => {
  						_result.push(key + '[]=' + _value)
  					})
  			}
  		} else {
  			_result.push(key + '=' + value)
  		}
  	}
  	return _result.length ? prefix + _result.join('&') : ''
  }
  
  export default queryParams;