Adding parameters to URL, putting array in query string

18,411

Solution 1

You can use an array directly in a url, however you would need to serialize the array into a string. like this player[]=one&player[]=two

here is a little function to automate it.

when using url's you should always use encodeURIComponent to encode any non url friendly characters. The players are an array so we map over it and get a new array that has been encoded.

After that we simply need to join the array with &

const players = [
  'player Name 1',
  'playerName2',
  'playerName3'
]

const parameterizeArray = (key, arr) => {
  arr = arr.map(encodeURIComponent)
  return '?'+key+'[]=' + arr.join('&'+key+'[]=')
}

console.log(parameterizeArray('player', players))

edit

The only difference is the function declaration style, everything else is standard ES5

function parameterizeArray(key, arr) {
  arr = arr.map(encodeURIComponent)
  return '?'+key+'[]=' + arr.join('&'+key+'[]=')
}

Solution 2

Cleanier:

website.com/?players=player1,player2,player3,player4

Then split the query to get result:

var arrayResult = query.players.split(",")
Share:
18,411
Andrew Nguyen
Author by

Andrew Nguyen

Updated on June 22, 2022

Comments

  • Andrew Nguyen
    Andrew Nguyen almost 2 years

    Objective

    I've built an interactive where people can choose six players to make their all-star team. When they click share to Twitter, my hope is to have a URL containing parameters of all six players something like website.com/?playerName=picked?playerName=picked so that people can share their teams

    Question

    • What is the best way to append parameters to a URL?
    • How do you put an array into a query string?