Thursday, January 22, 2026
HomeLanguagesJavascriptHow to Create Query Parameters in JavaScript ?

How to Create Query Parameters in JavaScript ?

The task is to create a query URL for GET request given a JSON object using javaScript. GET query parameters in an URL are just a string of key-value pairs connected with the symbol &. To convert a JSON object into a GET query parameter we can use the following approach.

  • Make a variable query.
  • Loop through all the keys and values of the json and attach them together with ‘&’ symbol.

Examples:

Input: {'website':'neveropen', 'location':'india'}
Output: website=neveropen&location=india

Syntax:

function encodeQuery(data){
    let query = ""
    for (let d in data)
         query += encodeURIComponent(d) + '=' + 
            encodeURIComponent(data[d]) + '&'
    return query.slice(0, -1)
}

Below examples implements the above approach:

Example 1:




<script>
function encodeQuery(data){
    let query = ""
    for (let d in data)
         query += encodeURIComponent(d) + '=' 
                  + encodeURIComponent(data[d]) + '&'
    return query.slice(0, -1)
}
  
// Json object that should be
// converted to query parameter
data = { 
    'website':'neveropen',
    'location':'india'
}
queryParam = encodeQuery(data)
console.log(queryParam)
</script>


Output:

website=neveropen&location=india

Example 2: In this example, we will create a complete URL from the given JSON data.




<script>
function encodeQuery(data){
    let query = data.url
    for (let d in data.params)
         query += encodeURIComponent(d) + '='
              + encodeURIComponent(data.params[d]) + '&';
    return query.slice(0, -1)
}
  
// Json object that should be
// converted to query parameter
data = { 
    url : 'www.neveropen.com/',
    params : {
        'website':'neveropen',
        'location':'india'
    }
}
queryParam = encodeQuery(data)
console.log(queryParam)
</script>


Output:

www.neveropen.com/website=neveropen&location=india
RELATED ARTICLES

Most Popular

Dominic
32475 POSTS0 COMMENTS
Milvus
119 POSTS0 COMMENTS
Nango Kala
6847 POSTS0 COMMENTS
Nicole Veronica
11977 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12064 POSTS0 COMMENTS
Shaida Kate Naidoo
6986 POSTS0 COMMENTS
Ted Musemwa
7220 POSTS0 COMMENTS
Thapelo Manthata
6933 POSTS0 COMMENTS
Umr Jansen
6912 POSTS0 COMMENTS