我有一个这样的字符串:
abc=foo&def=%5Basf%5D&xyz=5
如何将其转换为这样的JavaScript对象?
{
abc: 'foo',
def: '[asf]',
xyz: 5
}
我有一个这样的字符串:
abc=foo&def=%5Basf%5D&xyz=5
如何将其转换为这样的JavaScript对象?
{
abc: 'foo',
def: '[asf]',
xyz: 5
}
当前回答
ES6一行(如果我们可以这样称呼它,看到长行)
[…新URLSearchParams (location.search) .entries())。Reduce ((prev, [key,val]) => {prev[key] = val;返回prev}, {})
其他回答
我也遇到了同样的问题,尝试了这里的解决方案,但没有一个真正有效,因为我在URL参数中有数组,像这样:
?param[]=5¶m[]=8&othr_param=abc¶m[]=string
所以我最终写了我自己的JS函数,它使一个数组的参数在URI:
/**
* Creates an object from URL encoded data
*/
var createObjFromURI = function() {
var uri = decodeURI(location.search.substr(1));
var chunks = uri.split('&');
var params = Object();
for (var i=0; i < chunks.length ; i++) {
var chunk = chunks[i].split('=');
if(chunk[0].search("\\[\\]") !== -1) {
if( typeof params[chunk[0]] === 'undefined' ) {
params[chunk[0]] = [chunk[1]];
} else {
params[chunk[0]].push(chunk[1]);
}
} else {
params[chunk[0]] = chunk[1];
}
}
return params;
}
如果你正在使用URI.js,你可以使用:
https://medialize.github.io/URI.js/docs.html#static-parseQuery
var result = URI.parseQuery("?foo=bar&hello=world&hello=mars&bam=&yup");
result === {
foo: "bar",
hello: ["world", "mars"],
bam: "",
yup: null
};
//under ES6
const getUrlParamAsObject = (url = window.location.href) => {
let searchParams = url.split('?')[1];
const result = {};
//in case the queryString is empty
if (searchParams!==undefined) {
const paramParts = searchParams.split('&');
for(let part of paramParts) {
let paramValuePair = part.split('=');
//exclude the case when the param has no value
if(paramValuePair.length===2) {
result[paramValuePair[0]] = decodeURIComponent(paramValuePair[1]);
}
}
}
return result;
}
许多其他的解决方案没有考虑到边界情况。
这个可以处理
空键a=1&b=2& 空值a=1&b 空值a=1&b= 未编码的等号a=1&b=2=3=4
decodeQueryString: qs => {
// expects qs to not have a ?
// return if empty qs
if (qs === '') return {};
return qs.split('&').reduce((acc, pair) => {
// skip no param at all a=1&b=2&
if (pair.length === 0) return acc;
const parts = pair.split('=');
// fix params without value
if (parts.length === 1) parts[1] = '';
// for value handle multiple unencoded = signs
const key = decodeURIComponent(parts[0]);
const value = decodeURIComponent(parts.slice(1).join('='));
acc[key] = value;
return acc;
}, {});
},
ES6有一个非常简单而不正确的答案:
console.log(
Object.fromEntries(new URLSearchParams(`abc=foo&def=%5Basf%5D&xyz=5`))
);
但是这一行代码不包括多个相同的键,你必须使用更复杂的东西:
function parseParams(params) {
const output = [];
const searchParams = new URLSearchParams(params);
// Set will return only unique keys()
new Set([...searchParams.keys()])
.forEach(key => {
output[key] = searchParams.getAll(key).length > 1 ?
searchParams.getAll(key) : // get multiple values
searchParams.get(key); // get single value
});
return output;
}
console.log(
parseParams('abc=foo&cars=Ford&cars=BMW&cars=Skoda&cars=Mercedes')
)
代码将生成如下结构:
[
abc: "foo"
cars: ["Ford", "BMW", "Skoda", "Mercedes"]
]