gpt4 book ai didi

javascript - 从 URLSearchParams 获取对象数组

转载 作者:行者123 更新时间:2023-12-04 14:05:26 32 4
gpt4 key购买 nike

我需要提取 filter这是来自 URL 字符串的对象数组:http://localhost:3006/menus?page=1&filter[0][id]=MenuID&filter[0][value]=2&filter[1][id]=ParentMenuName&filter[1][value]=u .
这是目前我所拥有的:

  const location = useLocation();
const searchParams = new URLSearchParams(location.search);
const filterParamsValue = searchParams.getAll('filter'); // returns []
这是我想从 filter 得到的:
[ { id: 'MenuID', value: '2' }, { id: 'ParentMenuName', value: 'u' } ]

最佳答案

一些快速的功能:D ...

let s = `http://localhost:3006/menus?page=1&filter[0][id]=MenuID&filter[0][value]=2&filter[1][id]=ParentMenuName&filter[1][value]=u`

// get just array of strings like ['filter[0][id]=MenuID', ...]
let arr = s.split(/\&/).slice(1)
let filters = {}

arr.forEach(f => {
const id = f.match(/\[([\d]+)\]/)[1]
const prop = f.match(/\[([a-z]+)\]/)[1]

if(filters[id]) {
filters[id][prop] = f.match(/=([\w]+)/)[1]
} else {
filters[id] = {}
filters[id][prop] = f.match(/=([\w]+)/)[1]
}
})


// show filters object:
console.dir( filters )

/*

{
0: { id: "MenuID", value: "2"},
1: { id: "ParentMenuName", value: "u"}
}

*/

这为您提供了过滤器对象。
如果需要数组,可以将其转换为:
/**
* get object of filters and make an array of filters
*/
const arrayOfFilters = []

for(key in filters) {
arrayOfFilters.push(filters[key])
}

console.log(arrayOfFilters)

关于javascript - 从 URLSearchParams 获取对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68724550/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com