Object to Query String

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will explore how to generate a query string from the key-value pairs of an object using JavaScript. We will use the Array.prototype.reduce() method on Object.entries() to create the query string and determine the appropriate symbol to be used based on the length of the queryString. By the end of this lab, you will be able to efficiently generate a query string for your web applications.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/AdvancedConceptsGroup(["`Advanced Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/BasicConceptsGroup -.-> javascript/obj_manip("`Object Manipulation`") javascript/AdvancedConceptsGroup -.-> javascript/higher_funcs("`Higher-Order Functions`") javascript/AdvancedConceptsGroup -.-> javascript/destr_assign("`Destructuring Assignment`") javascript/AdvancedConceptsGroup -.-> javascript/template_lit("`Template Literals`") subgraph Lab Skills javascript/variables -.-> lab-28524{{"`Object to Query String`"}} javascript/data_types -.-> lab-28524{{"`Object to Query String`"}} javascript/arith_ops -.-> lab-28524{{"`Object to Query String`"}} javascript/comp_ops -.-> lab-28524{{"`Object to Query String`"}} javascript/obj_manip -.-> lab-28524{{"`Object to Query String`"}} javascript/higher_funcs -.-> lab-28524{{"`Object to Query String`"}} javascript/destr_assign -.-> lab-28524{{"`Object to Query String`"}} javascript/template_lit -.-> lab-28524{{"`Object to Query String`"}} end

Converting Object to Query String

To convert an object to a query string, use objectToQueryString() function which generates a query string from the key-value pairs of the given object.

The function works as follows:

  • It uses Array.prototype.reduce() on Object.entries() to create the query string from queryParameters.
  • It determines the symbol to be either ? or & based on the length of queryString.
  • It concatenates val to queryString only if it's a string.
  • It returns the queryString or an empty string when the queryParameters are falsy.

Here's the code for objectToQueryString() function:

const objectToQueryString = (queryParameters) => {
  return queryParameters
    ? Object.entries(queryParameters).reduce(
        (queryString, [key, val], index) => {
          const symbol = queryString.length === 0 ? "?" : "&";
          queryString +=
            typeof val === "string" ? `${symbol}${key}=${val}` : "";
          return queryString;
        },
        ""
      )
    : "";
};

Example usage of objectToQueryString() function:

objectToQueryString({ page: "1", size: "2kg", key: undefined }); // returns '?page=1&size=2kg'

Summary

Congratulations! You have completed the Object to Query String lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like