1

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.

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

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.