Convert Array to Query string using JavaScript

Mahabubur Rahman
0


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: "mahabub@exampla.com", phone: "0897788665" }));
Output:
email=mahabub%40exampla.com&phone=0897788665

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

let object = {
    email: "mahabub@exampla.com",     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: "mahabub@exampla.com",     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: "mahabub@exampla.com", phone: "0897788665" } undefined Object.keys(obj).map(k => `${encodeURIComponent(k)}=${encodeURIComponent(obj[k])}`).join('&'); 'email=mahabub%40exampla.com&phone=0897788665'

 

Post a Comment

0Comments
Post a Comment (0)