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

Viewed 1061

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

0 Answers
Related