How to usekeys() and map() Methods in JQuery
- Declare an object and store it in the variable.
- Use JSON.stringify() method to convert the object into strings and display the string contents.
- Click on the button to call the convert() function which converts the serialized object to a query string.
- The convert() function uses the keys() and map() methods to convert the serialized object to a query string.
Example: This example creates a function which is taking each key, and value pair and appends them as a string to get the query string keys() and map() method.
html
<!DOCTYPE html> < html lang = "en" > < head > < title > Serialize an object to query string </ title > < script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js" > </ script > </ head > < body > < h1 style = "color:green;" > w3wiki </ h1 > < p > Click the button to serialize the object to query string </ p > < button > click here </ button > < p id = "result" ></ p > < script > const data = { param1: 'val_1', param2: 'val_2', param3: 'val_3' }; JSON.stringify(data); function convert(json) { return '?' + Object.keys(json).map(function (key) { return encodeURIComponent(key) + '=' + encodeURIComponent(json[key]); }).join('&'); } $('button').on('click', function () { const result = convert(data); $('#result').text(result); }); </ script > </ body > </ html > |
Output:
How to serialize an object to query string using jQuery ?
Given a jQuery object and the task is to serialize the object element into the query string using jQuery. To serialize an object we can use different approaches.
Below are the following approaches:
- Using JSON.stringify() method and jQuery() param() Method
- Using keys() and map() Methods
Contact Us