Nicolas
Nicolas

Reputation: 4756

using an Array in a GET request

I have an array which looks like this languages = [1,2,3,4,5]

The API call expects the url parameter to be languages=1&languages=2&...

how can I achieve this with javascript?

I've tried JSON.stringify(languages); & just sending the languages variable, but I don't get the desired result.

I can also loop over the array and always add &languages=number to a string, but I figured the would be a more efficient way?

Thanks in advance

Upvotes: 1

Views: 4267

Answers (2)

jperelli
jperelli

Reputation: 7197

Another option using Array.prototype.join

var languages = [2,4,6,8]

lang_params = 'languages='+languages.join('&languages=')

console.log(lang_params)

(as per @Quentin and @Amit comments) If you work with other params that are not integer, you might need to encode the values so they don't interfere with special symbols (i.e. &,?). In such case, you can use encodeURI

lang_params = languages.map((l)=>'languages='+encodeURIComponent(l)).join('&')

Upvotes: 6

Quentin
Quentin

Reputation: 943651

The URISearchParams API will handle this case cleanly.

It will also do any escaping of the data that is required to make the values or keys URL safe (in your particular example this doesn't matter, but it is worth paying attention to for the general case).

// Create an object to describe the data in the query string
var query = new URLSearchParams();

// Add the languages
var languages = [1,2,3,4,5]
languages.forEach(function (language) {
    query.append("language", language);
});

// Explicitly convert to a string
console.log(query.toString());

Note there is limited browser support at present, so you will probably wish to use a polyfill.

Upvotes: 2

Related Questions