Converting a Javascript Dictionary To GET URL Parameters

Converting a Javascript Dictionary To GET URL Parameters

I've had serveral instances in the recent past where I needed to take a javascript dictionary and convert it into a set of GET parameters to be used in a URI. Usually this happens when I'm building an AJAX request.

Anyway, since I've used this function over and over I thought I'd post it incase it helps any of you Googling for something similar. Here's the function...

Pause reading for 5 seconds...
Join My Mailing List!
Note: I will never share your email with anyone else.
Awesome! Thanks so much.
Submitting...
Ok, lets continue.

Javascript to convert a javascript dictionary to GET parameters

function dictToURI(dict) {
  var str = [];
  for(var p in dict){
     str.push(encodeURIComponent(p) + "=" + encodeURIComponent(dict[p]));
  }
  return str.join("&");
}

You might use it in a case like this...

var myKeyValues = {
  "key1" : "value1",
  "key2" : "value2",
  "key3" : "value3"
}

var ajaxURL = "http://api.mattcrampton.com/xyz?" + dictToURI(myKeyValues);

Which sets ajaxURL to...

http://api.mattcrampton.com/xyz?key1=value1&key2=value2&key3=value3

P.S. If you're pushing this to a static hosted site on S3, be sure to read my post on Cloudfront Invalidation

Post A Twitter Response To This Blog Post

To: @mattccrampton

0