zoukankan      html  css  js  c++  java
  • JavaScript实现对象转URL参数

    在JavaScript中发送请求的时候,有的时候参数是对象类型,而get请求参数是拼接在URL中,因此通过以下代码实现参数转换:

    /**
     * 对象转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;
  • 相关阅读:
    软件需求与分析课堂讨论
    Axios
    lodash
    table行拖拽
    js addDays ,addYears
    所在周的第一天
    Inner join case when
    npm 淘宝镜像安装以及安装报错window_nt 6.1.7601 解决
    jsTree
    Bootstrap Multiselect
  • 原文地址:https://www.cnblogs.com/cap-rq/p/13615310.html
Copyright © 2011-2022 走看看