How to serialize an object into a list of URL query parameters using JavaScript ?
Last Updated :
20 Jun, 2023
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.
Javascript
let obj = {
p1: 'GFG' ,
p2: 'Geeks' ,
p3: 'GeeksForGeeks'
}
console.log(JSON.stringify(obj));
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.
Javascript
let obj = {
p1: 'GFG' ,
p2: 'Geeks' ,
p3: 'GeeksForGeeks'
}
console.log(JSON.stringify(obj));
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'
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...