Mulot
Mulot

Reputation: 311

Replace an array parameter in a url request using URLSearchParams and $.param()

I would like to change the url request while clicking on a link one of the element of an array. For example :

?foo[]=1&foo[]=2

to

?foo[]=1&foo[]=3

I use URLSearchParams with methods .getAll('foo[]') and then .set('foo[]', array) Finally, I use jquery method param() to generate a correct url string (as I was not able to use URLSearchParams.toString() with an array -- the result is always foo[]=1&3).

This is working, but if I had other parameter in the request I would like to keep, it becomes complicated to regenerate the url.

For example :

?foo[]=1&foo[]=2&bar=3&bar[]=4&page=1

to

?foo[]=1&foo[]=3&bar=3&bar[]=4&page=1

I have many parameters, so I would like to avoid the rebuild the entire query object to pass to $.param(). So :

  1. Is there any option to get the whole array from URLSearchParams without using any loop.
  2. Is there any trick to use URLSearchParams.toString() with arrays.

Upvotes: 1

Views: 1968

Answers (1)

Phil
Phil

Reputation: 164760

What you'll need to do is remove the foo[] entry, then iterate the values array from .getAll('foo[]') and .append().

For example

const usp = new URLSearchParams([
  ['foo[]', 1],
  ['foo[]', 2],
  ['bar', 3],
  ['bar[]', 4],
  ['page', 1]
])

console.info('original:', decodeURIComponent(usp.toString()))

// get all 'foo[]' entries
const foos = usp.getAll('foo[]')
// incremenent the last value
foos[foos.length - 1]++

// remove 'foo[]'
usp.delete('foo[]')

// iterate values and append
foos.forEach(foo => usp.append('foo[]', foo))

console.info('updated:', decodeURIComponent(usp.toString()))

Upvotes: 1

Related Questions