How to serialize an object into a list of URL query parameters using JavaScript ?
Last Updated :
20 Jun, 2023
Improve
Given a JavaScript Object and the task is to serialize it into a URL query parameters using JavaScript.
Approach 1:
- Declare an object and store it in the variable.
- Then use JSON.stringify() method to convert a JavaScript object into strings and display the content.
- Next, take an empty string and append (key, value) pairs of objects to it by accessing every property of the object.
Example: This example serializes an object into a list of URL query parameters using JavaScript.
// Declare an object
let obj = {
p1: 'GFG',
p2: 'Geeks',
p3: 'GeeksForGeeks'
}
// Use JSON.stringify() function to
// convert object into string
console.log(JSON.stringify(obj));
// Function to Serialize an Object into a
// list of URL query parameters
function GFG_Fun() {
let s = "";
for (let key in obj) {
if (s != "") {
s += "&";
}
s += (key + "=" + encodeURIComponent(obj[key]));
}
console.log("'" + s + "'");
}
GFG_Fun();
Output
{"p1":"GFG","p2":"Geeks","p3":"GeeksForGeeks"} 'p1=GFG&p2=Geeks&p3=GeeksForGeeks'
Approach 2:
- Declare an object and store it in the variable.
- Then use JSON.stringify() method to convert a JavaScript object into string and display the content.
- Use map() method to append the object key-value pair and use join() method to join all object elements.
Example: This example uses the map() method and appends each key, and value pair to a string.
// Declare an object
let obj = {
p1: 'GFG',
p2: 'Geeks',
p3: 'GeeksForGeeks'
}
// Use JSON.stringify() function to
// convert object into string
console.log(JSON.stringify(obj));
// Function to Serialize an Object into a
// list of URL query parameters
function GFG_Fun() {
let s = Object.keys(obj).map(function (key) {
return key + '=' + obj[key];
}).join('&');
console.log("'" + s + "'");
}
GFG_Fun();
Output
{"p1":"GFG","p2":"Geeks","p3":"GeeksForGeeks"} 'p1=GFG&p2=Geeks&p3=GeeksForGeeks'