js中get要求中将json花样的对象拼接成庞杂的url参数

const url=”/mock/products”

const query={pageIndex: 1, pageSize: 5}

  • 要领一
const serialize = function(obj) {
            var ary = [];
            for (var p in obj)
                if (obj.hasOwnProperty(p) && obj[p]) {
                    ary.push(encodeURIComponent(p) + '=' + encodeURIComponent(obj[p]));
                }
            return ary.join('&');
        };
  • 要领二

使用了antd,form表单会有undefined的时刻,map要领会把undefined也拼接上去。须要处置惩罚query。

const queryStr = Object.keys(query)
            .map(key => query[key] && `${encodeURIComponent(key)}=${encodeURIComponent(query[key])}`)
            .join('&');
  • 要领三
const queryStr = Object.keys(query)
            .reduce((ary, key) => {
                if (query[key]) {
                    ary.push(encodeURIComponent(key) + '=' + encodeURIComponent(query[key]));
                }
                return ary;
            }, [])
            .join('&');
url += `?${queryStr}`;
    原文作者:Tesla
    原文地址: https://segmentfault.com/a/1190000019112500
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞