19

I'd like to get something like

?key=value?key=value

out of a js dictionary that is

{
    key:value,
    key:value
}
tallowen
  • 4,198
  • 7
  • 27
  • 35
  • 6
    I think you mean `?key=value&key=value` :) – Nick Radford Aug 12 '11 at 19:03
  • 1
    Does this answer your question? [How to serialize an Object into a list of URL query parameters?](https://stackoverflow.com/questions/6566456/how-to-serialize-an-object-into-a-list-of-url-query-parameters) – jfunk Dec 16 '19 at 16:00

3 Answers3

29

If using jQuery, you can use jQuery.param:

var params = { width:1680, height:1050 };
var str = jQuery.param( params );
// str is now 'width=1680&height=1050'

Otherwise, here is a function that does it:

function serialize(obj) {
  var str = [];
  for(var p in obj)
     str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
  return str.join("&");
}
alert(serialize({test: 12, foo: "bar"}));
congusbongus
  • 13,359
  • 7
  • 71
  • 99
Alex Turpin
  • 46,743
  • 23
  • 113
  • 145
23

There is a much simpler way to do this now:

API for URLSearchParams is here

var url = new URL('https://example.com/');
url.search = new URLSearchParams({blah: 'lalala', rawr: 'arwrar'}); 
console.log(url.toString()); // https://example.com/?blah=lalala&rawr=arwrar
jfunk
  • 7,176
  • 4
  • 37
  • 38
  • 4
    You can convert the params only with toString method aswell: `var url = new URLSearchParams(params).toString();` – contmp Nov 22 '19 at 23:16
  • Not supported by IE11 as per https://caniuse.com/#search=URLSearchParams – patb Feb 28 '20 at 16:57
7

The same in ECMAScript 2016:

let params = { width:1680, height:1050 };
// convert object to list -- to enable .map
let data = Object.entries(params);
// encode every parameter (unpack list into 2 variables)
data = data.map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`);
// combine into string
let query = data.join('&');
console.log(query); // => width=1680&height=1050

Or, as single-liner:

let params = { width:1680, height:1050 };
Object.entries(params).map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`).join('&');
// => "width=1680&height=1050"
Artem Skoretskiy
  • 878
  • 10
  • 9
  • This works, thanks! Can you explain the backwards accent marks and dollar signs? I've not seen that before. – kloddant May 07 '20 at 13:54
  • 1
    @kloddant It is the same as ' or " except that you can embed expressions in it. Ex. `text ${1+1}` // will output "text 2" https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals – Mourad Qqch Jan 22 '21 at 12:19