Open In App

How to serialize an object into a list of URL query parameters using JavaScript ?

Given a JavaScript Object and the task is to serialize it into a URL query parameters using JavaScript. 

Approach 1:



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:

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'

Article Tags :