send key value pair array in url in javascript

In JavaScript, we can use the URLSearchParams API to easily create and append query strings to URLs. Here's an example:

index.tsx
const params = new URLSearchParams();
const myArray = [{key: 'fruit', value: 'apple'}, {key: 'name', value: 'John'}];

myArray.forEach(item => {
  params.append(item.key, item.value);
});

const queryString = params.toString();
const url = `https://example.com/api?${queryString}`;

console.log(url);
// Output: https://example.com/api?fruit=apple&name=John
358 chars
13 lines

In the above example, we create a new URLSearchParams object and append key-value pairs from the JavaScript array using a forEach() loop. Then, we call the toString() method on the URLSearchParams object to get the query string representation of the key-value pairs. Finally, we append the query string to our URL and log it to the console.

Note that you may need to encode URI components using encodeURIComponent() for certain characters in your key or value to avoid issues with URL encoding.

gistlibby LogSnag