将URL参数转换为JavaScript对象我有一根这样的绳子:abc=foo&def=%5Basf%5D&xyz=5如何将其转换为这样的JavaScript对象?{
abc: 'foo',
def: '[asf]',
xyz: 5}
3 回答
隔江千里
TA贡献1906条经验 获得超10个赞
编辑
var search = location.search.substring(1);JSON.parse('{"' + decodeURI(search).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g,'":"') + '"}')
例
abc=foo&def=%5Basf%5D&xyz=5
decdeURI:abc=foo&def=[asf]&xyz=5 转义引号:相同,因为没有引号 替换&: abc=foo","def=[asf]","xyz=5
取代=: abc":"foo","def":"[asf]","xyz":"5
有卷曲和引号: {"abc":"foo","def":"[asf]","xyz":"5"}
var search = location.search.substring(1);JSON.parse('{"' + search.replace(/&/g, '","').replace(/=/g,'":"') + '"}', function(key, value) { return key===""?value:decodeURIComponent(value) })
例
search = "abc=foo&def=%5Basf%5D&xyz=5&foo=b%3Dar";
Object {abc: "foo", def: "[asf]", xyz: "5", foo: "b=ar"}
原始答案
JSON.parse('{"' + decodeURI("abc=foo&def=%5Basf%5D&xyz=5".replace(/&/g, "\",\"").replace(/=/g,"\":\"")) + '"}')
潇潇雨雨
TA贡献1833条经验 获得超4个赞
let params = new URLSearchParams('abc=foo&def=%5Basf%5D&xyz=5');params.get("abc"); // "foo"
function paramsToObject(entries) { let result = {} for(let entry of entries) { // each 'entry' is a [key, value] tupple const [key, value] = entry; result[key] = value; } return result;}
基本演示
const urlParams = new URLSearchParams('abc=foo&def=%5Basf%5D&xyz=5');const entries = urlParams.entries(); //returns an iterator of decoded [key,value] tuplesconst params = paramsToObject(entries); //{abc:"foo",def:"[asf]",xyz:"5"}
使用Object.From Entry和Side
paramsToObject
Object.fromEntries(entries)
.
.entries
要迭代的值对是列表名称-值对,键是名称,值是值。
const urlParams = new URLSearchParams('abc=foo&def=%5Basf%5D&xyz=5');const params = Object.fromEntries(...params); // {abc: "foo", def: "[asf]", xyz: "5"}
注:
梵蒂冈之花
TA贡献1900条经验 获得超5个赞
&
=
var str = "abc=foo&def=%5Basf%5D&xy%5Bz=5"var obj = str.split("&").reduce(function(prev, curr, i, arr) { var p = curr.split("="); prev[decodeURIComponent(p[0])] = decodeURIComponent(p[1]); return prev;}, {});
var obj = {}; str.replace(/([^=&]+)=([^&]*)/g, function(m, key, value) { obj[decodeURIComponent(key)] = decodeURIComponent(value);});
- 3 回答
- 0 关注
- 473 浏览
添加回答
举报
0/150
提交
取消