-2

I want to stringify an object into a query string.

For example,

{ hello: '123', goodbye: "789" }

Would give me...

hello=123&goodbye=789
Brad Koch
  • 19,267
  • 19
  • 110
  • 137
TIMEX
  • 259,804
  • 351
  • 777
  • 1,080
  • It should be doable with loop and join. I don't think I have come across built-in JS function to do this, though. – nhahtdh Mar 01 '13 at 18:30
  • possible duplicate of [Serialize object to query string in JavaScript/jQuery](http://stackoverflow.com/questions/3308846/serialize-json-to-query-string-in-javascript-jquery) – Qantas 94 Heavy Jun 22 '14 at 04:07

3 Answers3

5

There is an excellent URL library, URL.js which works pretty much as you describe for queries.

For your example, the code would be:

URI().addSearch({ hello: '123', goodbye: "789" }).toString()

This produces the result with a pre-pended ?, but it comes in extremely handy for constructing & manipulating real URLs.

Barney
  • 16,181
  • 5
  • 62
  • 76
4

If case if you use jQuery in your project you don't need a lib for this:

$.param({ hello: '123', goodbye: "789" })

But since there is no jQuery tag, take a look at Barney answer, this is probably what you need.

dfsq
  • 191,768
  • 25
  • 236
  • 258
0

Here is a code sample for simple cases:

var params={ hello: '123', goodbye: "789" },
    pairs=[];
for (var key in params) {
    if (params.hasOwnProperty(key)) {
        pairs.push(key+"="+encodeURIComponent(params[key]));
    }
};
var qs=pairs.join("&");

For more complex scenarios you might want to use a library like URLjs as suggested in other replies.

Christophe
  • 27,383
  • 28
  • 97
  • 140