Convert Array to Query string using JavaScript

engrmahabub
Mahabubur Rahman
Published on Aug, 29 2023 1 min read 0 comments
image

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 as -

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

Output - 

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

Method 2 :

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

Output - 

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

Method 3 - 

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

Output -

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

Method 4 - 

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

Output - 

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

 

 

0 Comments