[英]How to convert url array query to object in Javascript
I have an URL with query params like this:我有一个带有查询参数的 URL,如下所示:
myLocalSite/?attributes%5B0%5D%5Bname%5D=customer_property_number&attributes%5B0%5D%5Bop%5D=equal&attributes%5B0%5D%5Bvalue%5D=12&attributes%5B1%5D%5Bname%5D=feedback_tags&attributes%5B1%5D%5Bop%5D=in&attributes%5B1%5D%5Bvalue%5D=test+1%2Cwww
after JSON parsing it convert into next structure JSON解析后转换为下一个结构
{
attributes[0][name]: "customer_property_number"
attributes[0][op]: "equal"
attributes[0][value]: "12"
attributes[1][name]: "feedback_tags"
attributes[1][op]: "in"
attributes[1][value]: "test 1,www"
}
In the end, I need an array that look like this:最后,我需要一个如下所示的数组:
attributes = [
{
name: 'customer_property_number',
op: 'equal',
value: '12',
},
{
name: 'feedback_tags',
op: 'in',
value: 'test 1, www',
},
]
Now does anyone know how I can then put these items into attributes array?现在有谁知道我如何将这些项目放入属性数组中?
Thanks!谢谢!
Here is the approach using URLSearchParams
and going over each search param, parse and push to array of objects.这是使用
URLSearchParams
并遍历每个搜索参数、解析并推送到对象数组的方法。
var sp = new URLSearchParams( "myLocalSite/?attributes%5B0%5D%5Bname%5D=customer_property_number&attributes%5B0%5D%5Bop%5D=equal&attributes%5B0%5D%5Bvalue%5D=12&attributes%5B1%5D%5Bname%5D=feedback_tags&attributes%5B1%5D%5Bop%5D=in&attributes%5B1%5D%5Bvalue%5D=test+1%2Cwww" ); var attributes = []; for (entry of sp) { const [attr, value] = entry; const [index, key] = attr .split("[") .filter(x => x.includes("]")) .map(x => x.slice(0, -1)); if (!attributes[Number(index)]) { attributes[Number(index)] = {}; } attributes[Number(index)][key] = value; } console.log(attributes);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.