objToUrl

34 阅读1分钟

将post数据字符串化

// 对象分支
function toObj(params) {
    let str = "";
    Object.keys(params).forEach((key) => {
        str += `.${key.toString()}${judge(params[key])}`;
    });
    return str;
}
// 数组分支
function toArr(params) {
    let str = "";
    params.forEach((item, index) => {
        str += `[${index.toString()}]${judge(item)}`;
    });
    return str;
}
// 分支判断
function judge(data) {
    if (data instanceof Array) {
        return toArr(data);
    } else if (data instanceof Object) {
        return toObj(data);
    }
    return `=${encodeURI(data.toString())}&`;
}
// url格式化
function frame(params) {
    params = params.replace(/\&\.+/gim, "&");
    params = params.replace(/^\./, "");
    params = params.replace(/\=\&$/i, "");
    params = params.replace(/\&$/i, "");
    return params;
}
// 对外处理接口
function objToUrl(params) {
    return frame(judge(params));
}
module.exports = {
    objToUrl,
};