首页 > 解决方案 > 如何从 url 查询字符串,javascript 中获取关联数组

问题描述

我有 url 查询字符串

?filter%5B%22customer_rating_heading%22%5D=customer_rating_6_up%2Ccustomer_rating_7_up%2Ccustomer_rating_9_up&map=1

这是

?filter["customer_rating_heading"]=customer_rating_6_up,customer_rating_7_up,customer_rating_9_up&map=1

我想要求filter喜欢params.get('filter)并得到

[customer_rating_heading => 'customer_rating_6_up,customer_rating_7_up,customer_rating_9_up' //(later I'll make array from this string)

但我不知道该怎么做,我试过let query = Object.fromEntries(new URLSearchParams(location.search)但它给了我:

{filter["customer_rating_heading"]: "customer_rating_6_up,customer_rating_7_up,customer_rating_9_up"
map: "1"}

但我无法得到过滤器,就像query.filter它总是未定义一样

有人知道此类问题的解决方案吗?

标签: javascript

解决方案


用“匹配”解决

let query = Object.fromEntries(new URLSearchParams(location.search))

let firstKey = Object.keys(query)[0];
let found = firstKey.match(/\[(.*)\]/)[1]

let key = found.replace(/\"/g, '');
let value = query[firstKey];



console.log(`${key} => ${value}`)


推荐阅读