我有这个网址:
http://localhost:5000/?orderID=000000034&fullname=Leonard+Niehaus&email=test%40gmail.com&items%5B0%5D%5BitemId%5D=9&items%5B0%5D%5Btitle%5D=Joghurt&items%5B0%5D%5Bqty%5D=1.0000&items%5B1%5D%5BitemId%5D=8&items%5B1%5D%5Btitle%5D=Alpenmilch&items%5B1%5D%5Bqty%5D=1.0000
现在,我正在尝试将URL编码为对象。这是我目前的尝试:
function URLToArray(url) {
var request = {};
var pairs = url.substring(url.indexOf('?') + 1).split('&');
for (var i = 0; i < pairs.length; i++) {
if(!pairs[i])
continue;
var pair = pairs[i].split('=');
request[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
}
return request;
}
但是我需要此函数将数组作为JSON数组返回,而不是当前的方式:
如何获得函数以返回对象数组?
您首先可以使用help from this question获取对象。
[将URLSearchParams与正则表达式循环一起使用的示例:
const url = "http://localhost:5000/?orderID=000000034&fullname=Leonard+Niehaus&email=test%40gmail.com&items%5B0%5D%5BitemId%5D=9&items%5B0%5D%5Btitle%5D=Joghurt&items%5B0%5D%5Bqty%5D=1.0000&items%5B1%5D%5BitemId%5D=8&items%5B1%5D%5Btitle%5D=Alpenmilch&items%5B1%5D%5Bqty%5D=1.0000";
const regex = /^([a-z0-9]+)?\[([a-zA-Z0-9]+)\]*/mi;
function URLToArray(url) {
url = decodeURIComponent(url);
const args = new URLSearchParams(url.split('?')[1]);
let request = {};
args.forEach((value, key) => {
let baseKey = key;
let ogValue = value;
let lastKey = '';
while ((m = regex.exec(key)) !== null) {
if (m[1]) {
baseKey = m[1];
value = request[baseKey] || {};
request[baseKey] = value;
}
if (m[2]) {
value = value[lastKey] || value;
value[m[2]] = value[m[2]] || {};
lastKey = m[2];
}
key = key.replace(m[0], '');
}
if (lastKey) {
value[lastKey] = ogValue;
} else {
request[baseKey] = value;
}
});
return request;
}
console.log(URLToArray(url));
这不是完美的,与items
的适当数组相反,您将剩下嵌套对象,并且可能有一些库可以更好地达到相同的结果。