Suppose that I have the following dictionary:
var d = {
'foo': 0,
'bar': 1
};
How can I easily convert it to string like this?
foo=0&bar=1
Is there any built-in methods that can help me with it?
Not sure about built-in methods, but you can simply do
Object.keys( d ).map( function(key){ return key+"="+d[key] }).join("&") //outputs "foo=0&bar=1"
If you are using jQuery use $.param(data, true);
Or, For pure javascript you can use
function serialize(obj) {
var str = [];
for(var p in obj)
if (obj.hasOwnProperty(p)) {
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
}
return str.join("&");
}
serialize(data);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With