Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to "join" dictionary elements

Tags:

javascript

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?

like image 475
FrozenHeart Avatar asked Jan 18 '26 15:01

FrozenHeart


2 Answers

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"
like image 125
gurvinder372 Avatar answered Jan 20 '26 03:01

gurvinder372


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);
like image 42
Vinoth Rajendran Avatar answered Jan 20 '26 04:01

Vinoth Rajendran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!