2

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?

5
  • Does this make sense? Do you send that query to a server driven application or middleware? If so you can only get one role or source parameter from the query. Commented May 4, 2020 at 21:55
  • this is only half the query for the API, there are other variables that aren't relevant to the question Commented May 4, 2020 at 21:57
  • 1
    @marcel nope, that's how you pass arrays through queries (if you have to) Commented May 4, 2020 at 21:58
  • 1
    Well ... didn 't knew that. I have always done well with role[]=SW&role[]=EW. Nice to know. Thanks for the clarification. Commented May 4, 2020 at 22:02
  • 1
    @marcel yes, seen both. Finally looked it up, seems as if this is not specified at all (not even the &, = syntax), so all of this actually depends on how your backend handles it. So my previous comment doesnt make that much sense, sorry. Commented May 4, 2020 at 22:06

2 Answers 2

3

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("&");
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, this is perfect!
String should be not a "a=1&a=2" but "a[]=1&a[]=2"
2

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()
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.