;

How to Convert an Object into Query String Parameters in JavaScript


Tutorialsrack 19/03/2022 Jquery Javascript

In this article, you’ll learn how to convert an object into QueryString parameters in Javascript. sometimes, you'll often need to construct URLs and query string parameters. One sensible way to construct query string parameters is to use a one-layer object with key-value pairs.

In this article, we'll cover various ways to turn an object into QueryString parameters like this:

var params = {
    price: "900",
    size: ["M", "XL"],
    sort: "desc",
};

Example 1: Using map() and join() Function

In this example, you can use map() function to create an array of strings like price=900, then use join() function to join them together with &.

Example: ES6

var params = {
    price: "900",
    size: ["M", "XL"],
    sort: "desc",
};


var queryString = Object.keys(params).map(key => key + '=' + params[key]).join('&');

console.log(queryString)
//Output ==> price=900&size=M,XL&sort=desc

Example: ES5

var params = {
    price: "900",
    size: ["M", "XL"],
    sort: "desc",
};

var queryString = Object.keys(params).map(function(key) {
    return key + '=' + params[key]
}).join('&');

console.log(queryString)
//Output ==> price=900&size=M,XL&sort=desc

Example 2: Using jQuery

In this example, you need to use the jquery library and jquery provides a function $.param() which converts an object into query string parameters.

var params = {
    price: "900",
    size: ["M", "XL"],
    sort: "desc",
};

var queryString = $.param(params);


console.log(queryString)
//Output ==> price=900&size%5B%5D=M&size%5B%5D=XL&sort=desc

I hope this article will help you to understand how to convert an object into QueryString parameters in Javascript.

Share your valuable feedback, please post your comment at the bottom of this article. Thank you!


Related Posts



Comments

Recent Posts
Tags