Convert 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...

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 = "" + dictToURI(myKeyValues);

Which sets ajaxURL to...

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

See all blog posts or go back to Matt Crampton