Categories
JavaScript Answers

How to pass an array as a URL parameter with JavaScript?

Spread the love

Sometimes, we want to pass an array as a URL parameter with JavaScript.

In this article, we’ll look at how to pass an array as a URL parameter with JavaScript.

How to pass an array as a URL parameter with JavaScript?

To pass an array as a URL parameter with JavaScript, we can create our own query string with the values.

For instance, we write

const myArray = ["aaa", "bbb", "ccc"];

const myArrayQry = myArray
  .map((el, idx) => {
    return `myArray['${idx}']=${el}`;
  })
  .join("&");

to call map with a function that returns the query string part with "myArray['${idx}']" as the key and el as its value.

idx is the index of the item in myArray.

Conclusion

To pass an array as a URL parameter with JavaScript, we can create our own query string with the values.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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