invrt
invrt

Reputation: 709

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

my object looks like this

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&source=Tertiary&role=SW&role=EW

Could anyone help me out?

Upvotes: 2

Views: 1501

Answers (2)

Salmin Skenderovic
Salmin Skenderovic

Reputation: 1720

You can use URLSearchParam and iterate over the Object.keys and then each of the values

https://developer.mozilla.org/en-US/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()
)

Upvotes: 2

Jonas Wilms
Jonas Wilms

Reputation: 138267

You could flatMap the Object entries:

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

Upvotes: 2

Related Questions