Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

URLSearchParams with multiple values

I have multiples URLSearchParams created from object mainly because it’s lighter to write and to read but for some of them, I need multiple values for a "variable" like this : foo=bar&foo=baz.
For now I do it with .append but it’s heavy to read having multiple lines pretty identical.
Is there a way to do it from the constructor, with an object ?

let params;

// Currently used (and working) code
params = new URLSearchParams()
params.append("foo", "bar");
params.append("foo", "baz");

console.log(params.toString()); //Wanted result but heavy to read with more values

// Wanted code (but not the wanted result for now)

params = new URLSearchParams({
    "foo": ["bar", "baz"]
});

console.log(params.toString());

params = new URLSearchParams({
    "foo": "bar",
    "foo": "baz"
});

console.log(params.toString());

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The URLSearchParams can takes an init value as argument for its constructor containing the following:

One of:

  • A string, which will be parsed from application/x-www-form-urlencoded format. A leading '?' character
    is ignored.

  • A literal sequence of name-value string pairs, or any object — such as a FormData object — with an iterator that produces a sequence of
    string pairs. Note that File entries will be serialized as [object File] rather than as their filename (as they would in an
    application/x-www-form-urlencoded form).

  • A record of string keys and string values.

In your case the second one seems to work the best and can be done like this:

const searchParams = new URLSearchParams([['foo', 'bar'],['foo', 'baz'],['foo', 'qux']])

console.log(searchParams.toString())

If you want to deal with objects, you can create your own structure and use a function to create the wanted data

For example :

const params = [
  {name: "foo", values: ["bar", "baz", "qux"]},
  {name: "bar", values: ["foo", "foo2", "foo3"]},
]

const initParams = (params) => params.reduce((acc, curr) => {
  const arr = curr.values.map(x => [curr.name, x])
  return acc.concat(arr)
}, [])

const searchParams = new URLSearchParams(initParams(params))

console.log(searchParams.toString())
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading