Xen_mar
Xen_mar

Reputation: 9682

Combine two URLSearchParams()

Quick question:

Is it possible to combine two instances of URLSearchParams?

const params1 = new URLSearchParams();
const params2 = new URLSearchParams();

const finalParms = mergeThis(params1, params2) <- do this?

This question has been answered for angular but in plain JavaScript URLSearchParams has no member called .appendAll()

Thanks!

Upvotes: 4

Views: 3214

Answers (3)

Koleok
Koleok

Reputation: 591

Combining the two in a template works well as toString() is called on each implicitly.

const a = new URLSearchParams({ a: 1 })
const b = new URLSearchParams({ b: 2 })

const finalParms = `${a}&${b}` // 'a=1&b=2'

You could also make a simple util to do this like

const mergeParams = (...params) => params.map(String).join('&')
const finalParms = mergeParams(a, b) // 'a=1&b=2'

Upvotes: 0

Joshua Wade
Joshua Wade

Reputation: 5293

No, but you can make one with URLSearchParams.append():

function combineSearchParams(searchParams1, searchParams2) {
  const result = new URLSearchParams("");

  // Display the key/value pairs
  [searchParams1, searchParams2].map(params => {
    for(var pair of params.entries()) {
      result.append(pair[0], pair[1]);
    }
  });

  return result;
}

Then you can:

const searchParams1 =
  new URLSearchParams("key1=value1&key2=value2");
const searchParams2 =
  new URLSearchParams("key3=value3&key4=value4");

const combined =
 combineSearchParams(searchParams1, searchParams2);

// "key1=value1&key2=value2&key3=value3&key4=value4"
console.log(combined.toString());

Upvotes: 0

Quentin
Quentin

Reputation: 943517

There's no built-in method to do that, but you can simply loop over the entries and append them:

const params1 = new URLSearchParams("?foo=foo&bar=bar");
const params2 = new URLSearchParams("?baz=baz&nii=nii");
for (let [key, val] of params2.entries()) {
  params1.append(key, val);
}
console.log(params1.toString());

Upvotes: 16

Related Questions