Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fetch api - how to append an array as a search param

I'm trying to find out if there is a proper way to append an array to a url search-param using the native Fetch and URL APIs. For example - if I would like to append an array of one or more items to a list parameter.
For the moment I found this solution which works fine:

async function fetchList(array){
	const url = new URL('http://localhost:8080/some-route');
	
	array.forEach(item => url.searchParams.append('list[]', item));	

	const res = await fetch(url);
	return res.json();
}

fetchList(['item1','item2', 'item3'])

However, I was wondering if there is any native abstraction which might spare me iterating over the array and appending each of its items to 'list[]' (which feels a bit hacky..)

like image 956
itaydafna Avatar asked Sep 05 '25 03:09

itaydafna


1 Answers

There is no built in way to do a bulk add to an URLSearchParams. Either it needs to be a loop using URLSearchParams#append() as demonstrated in the question:

const array = ['item1', 'item2', 'item3'];

const url = new URL('http://localhost:8080/some-route');
array.forEach(item => url.searchParams.append('list[]', item));

console.log(url);

Or an alternative might be to generate a new URLSearchParams object since the constructor takes any iterable which produces key-value pairs:

const array = ['item1', 'item2', 'item3'];

const url = new URL('http://localhost:8080/some-route');

const newSearchParams = new URLSearchParams(array.map(x => ["list[]", x]));
url.search = newSearchParams;

console.log(url);

The new object needs to be assigned to the URL#search because URL#searchParams is readonly.

Technically search should be a string and URLSearchParameters#toString() is overloaded to provide a compatible search string. Thus url.search = newSearchParams.toString() would be more formally correct, however toString() is used by the implicit conversion anyway, so assigning the object still has the same result.

like image 95
VLAZ Avatar answered Sep 07 '25 21:09

VLAZ