Proper use of Arrays with UrlSearchParams

If you’re executing ‘get’ requests directly, you may sometimes need to send in an array of data. Below is an example of how to build the query string correctly using UrlSearchParamsmethod append:

var url = new URL(url ) // url is some url string

let searchParams =  new URLSearchParams({}); // you can pass in any initial data that you'd like here
let posts = get_my_post_array(); // returns an array of post ids
for(let post of posts){
    searchParams.append("post[]",post); // this is what 
    you need. Notice the square   brackets
} = searchParams.toString();
let json = fetch(url).then(response => response.json()); // and get the response

Now your back-end server will receive an array “post” with all the required Ids!

Thoughts? Comments? Let me know below.

Leave a Reply

Your email address will not be published. Required fields are marked *