Convert Array to Query string using JavaScript

Published 2 days ago5 min read4 comments

We can do it by some different way. Let see the bellow methods 

Method 1: Create a simple function as bellow -

let serialize = function(obj) {
  var str = [];
  for (var p in obj)
    if (obj.hasOwnProperty(p)) {
      str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
    }
  return str.join("&");
}

Call the function:

console.log(serialize({
  email: "[email protected]",
  phone: "0897788665"
}));

Output:

email=mahabub%40exampla.com&phone=0897788665

Method 2: Using URLSearchParams. It work in current all browser.

let object = {
      email: "[email protected]",
      phone: "0897788665"
    }
new URLSearchParams(object).toString()

Output:

'email=mahabub%40exampla.com&phone=0897788665'

Method 3 : jQuery.param() can also generate query string from js object.

let object = {
      email: "[email protected]",
      phone: "0897788665"
    }
var str = jQuery.param( object ); 
console.log(str);

Output :

email=mahabub%40exampla.com&phone=0897788665

Method 4: Using Object map

let obj = {
      email: "[email protected]",
      phone: "0897788665"
    }
undefined
Object.keys(obj).map(k => `${encodeURIComponent(k)}=${encodeURIComponent(obj[k])}`).join('&');

'email=mahabub%40exampla.com&phone=0897788665'


 

 

 

 

0 Comments