简体   繁体   English

将具有数组值的 object 键转换为查询字符串

[英]convert object key with array values to query string

I'm trying to convert my object to a query string but I have an array as the values我正在尝试将我的 object 转换为查询字符串,但我有一个数组作为值

my object looks like this我的 object 看起来像这样

filterChoice: { role: ["SW", "EW"] source: ["Secondary", "Tertiary"] }

I've gotten halfway with my conversion我的转变已经进行到一半

const toQueryString = `?${Object.keys(filterChoice)
    .map(key => `${key}=${filterChoice[key].toString()}`)
    .join('&')}`

which outputs: ?source=Secondary,Tertiary&role=SW,EW but I would like this output to look like this哪个输出: ?source=Secondary,Tertiary&role=SW,EW但我希望这个 output 看起来像这样

?source=Secondary&source=Tertiary&role=SW&role=EW

Could anyone help me out?谁能帮帮我?

You could flatMap the Object entries:您可以 flatMap Object 条目:

 const query = Object.entries(filterChoice)
  .flatMap(([key, value]) => [value].flat().map(v => [key, v]))
  .map(it => it.join("="))
  .join("&");

You can use URLSearchParam and iterate over the Object.keys and then each of the values您可以使用 URLSearchParam 并遍历 Object.keys 然后遍历每个值

https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams https://developer.mozilla.org/zh-CN/docs/Web/API/URLSearchParams

 var filterChoice = { role: ["SW", "EW"], source: ["Secondary", "Tertiary"] } var URL = "https://example.com/"; var searchParams = new URLSearchParams(URL); Object.keys(filterChoice).forEach(key => { filterChoice[key].forEach(val => { searchParams.append(key, val); }) }) console.log( searchParams.toString() )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM