我正在尝试将对象转换为查询字符串,但是我有一个数组作为值
我的对象看起来像这样
filterChoice: {
role: ["SW", "EW"]
source: ["Secondary", "Tertiary"]
}
我的转换已经中途了
const toQueryString = `?${Object.keys(filterChoice)
.map(key => `${key}=${filterChoice[key].toString()}`)
.join('&')}`
其输出:?source=Secondary,Tertiary&role=SW,EW
但我希望此输出看起来像这样
?source=Secondary&source=Tertiary&role=SW&role=EW
有人可以帮我吗?
答案 0 :(得分:3)
您可以flatMap对象条目:
const query = Object.entries(filterChoice)
.flatMap(([key, value]) => [value].flat().map(v => [key, v]))
.map(it => it.join("="))
.join("&");
答案 1 :(得分:0)
您可以使用URLSearchParam并依次遍历Object.keys和每个值
https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams
Function<Animal,?>