Combine request parameters and append them to the URL

When a user checks one or more of the four categories (Error, Warning, Info, and Debug) on my checkbox, I need to include them in an httpclient call query.

For instance, if all categories are checked, the query should look like this: (category=eq=Error,category=eq=Warning,category=eq=Info,category=eq=Debug)

I attempted to achieve this by creating a string object and concatenating each category if it is checked:

if (obj.category) {
      const ctgLength = obj.category.length; //number of categories checked by the user
      object["(category=eq"] = obj.category[0];
      for (let i = 1; i < ctgLength - 1; i++) {
      console.log(obj.category[i]);
      object[",category=eq"] = obj.category[i] + ",";
     }
     object["category=eq"] = obj.category[ctgLength - 1] + ")";
   }

However, the resulting query only includes the values from the last iteration of the loop, e.g., (category=eq=Error,category=eq=Info,category=eq=Debug).

My questions are: Firstly, is this method an effective way to generate a query for my situation? Secondly, how can I modify this code to ensure that all checked categories are included in the query?

Thank you.

Answer №1

In order to maintain code quality and clarity, it is essential to define any string literals as constants in a separate file. This practice promotes better organization and understanding for all individuals involved.

const StringConstants = {
  CategoryQueryParam: "category=eq"
};

Let's encapsulate that code within its own function:

function generateCategoryQueryString(selectedCategories) {}

We should also enhance the implementation a bit:

function generateCategoryQueryString (selectedCategories: string[]): string {
     if (selectedCategories == null || selectedCategories.length === 0) {
         return null;
     }
     let queryString = selectedCategories.map(category => 
     `${StringConstants.CategoryQueryParam}=${category}`).join(',');
     return `(${queryString})`;
}

Answer №2

When creating a loop in JavaScript, remember that indices start at 0, not 1.

The correct way to write a loop is:

for (let i = 0; i < ctgLength; i++) {

If you're used to programming in VB, you may find index handling in JavaScript to be different:

For example, when looping through an array in JavaScript:

var a = [0,1,2];<br />
==> a.length = 3<br />

To iterate over all elements, you would do something like this:

for(var i =0; i < 3; ++i) console.log(a[i]);

In VB, the syntax for looping is slightly different:

For i As Integer = 0 To 4 Step 1
    System.Console.WriteLine(i)
Next i

And for C-based languages, the equivalent loop would look like this:

for (let i = 0; i <= ctgLength; i++) { console.log(i);} 

Notice the use of <= instead of < in C based languages.

Therefore, in VB, you need to account for this difference by adding -1 to your loop limit:

For i As Integer = 0 To ctgLength-1 Step 1
. This adjustment is not necessary in C-based languages.

Answer №3

Do you think this solution would be effective?

const combinedCategories = obj.category.map(category => `category=eq=${category}`).join(',');
const combinedCategoriesEnclosedInBrackets = `(${combinedCategories})`

Update: @Mkdgs suggested using toString() instead of join to include commas by default.

const combinedCategories = obj.category.map(category => `category=eq=${category}`).toString();

Answer №4

Here is a quick solution:

data = {};
data.list = ['apple','orange','banana','grapes']; // assuming it's an array 

var output = '('+data.list.map( element =>  "item=eq="+element )+')';

console.log(output);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to prevent a high-powered Javascript loop from causing the browser to freeze

I am currently utilizing Javascript to parse an XML document containing roughly 3,500 elements. I have implemented a jQuery "each" function for this purpose, although I remain open to considering alternative looping methods. One issue that has surfaced ...

The sticky navigation bar unexpectedly jerks and creates a glitch

For the past few days, I've been grappling with a persistent issue that seems to be causing glitches on my site, especially when viewed on my iPhone. The problem lies in the sticky navbar, which snaps to the wrong place and jumps too fast when scrolli ...

Issues with Bootstrap tabs loading jQuery and Ajax are preventing the proper functionality

I am currently facing an issue with a tab pane designed using Bootstrap. The problem arises when attempting to load external pages into the tabs through Ajax using a jQuery script. While the ajax script successfully loads the content of the pages, I am en ...

How come Angular is recognizing my class as a module?

Recently, I've created a basic class that looks like this: export class User { id: number; username: string; password: string; firstName: string; lastName: string; token?: string; role?: string; dateCreated?: number; } ...

JavaScript code for sorting a table based on a time interval

There is an index file with a flight schedule table. The table allows sorting by airline and departure time, as well as filtering by airline name. I'm trying to figure out how to add filtering by time range, specifically departing flights between 8 AM ...

Issue encountered while trying to execute Reapp project demo

As I embark on setting up my initial Reapp project, I encounter a roadblock right at the start. A blank screen greets me, accompanied by a console error stating that main.js is not found (error 404). Upon executing reapp run -d, the following errors manif ...

Utilizing Angular PrimeNG's range datepicker, you can select a date range spanning from January 31st to December 1st, 2023 within a reactive form. Take it a step further by calculating

Here is some HTML code: <div class="row"> <div class="col-4"> <p-calendar label="startDate" formControlName="startDate" [minDate]="daMaxRange" ...

Assessing an angular equation enclosed in quotation marks in HTML

There was a situation where I encountered the need to assess an angular expression enclosed in quotes, as shown below <a href="mailto:{{account["email"]}}" However, the mentioned approach does not effectively evaluate the content within nested quotes ...

Steps for sending the form after completing validation

I have implemented a beautiful form with jQuery validation, but I'm unsure of where to place the function that should execute after the form has been validated. Below is the structure of the form: <form id="myForm" class="needs-vali ...

Selecting items in an HTML table using a drag-and-drop feature for selecting square or rectangular sections with colspan and rowspan

I am currently working on an implementation for selecting cells in a table. The challenge I am facing is that the cells in question can have a colspan or rowspan, which means that the selection is not restricted to a square or rectangular shape. For exampl ...

Taking an input value and transforming it into a percentage value to be utilized in a visual representation using a plotly pie chart

I am currently developing a budget calculator and I have a plan to convert user inputs into a pie chart. Once I figure out how to do this successfully, I can extend the same method to create charts for other sections as well. For testing purposes, let&apo ...

Definition for 'enhance' function type

I am currently working on defining a type for the evolve function from Ramda. The official definition provided does not seem to be functioning correctly. type Transformation<State> = { [Key in keyof State]: (x: State[Key]) => any } declare func ...

What is the best way to reference a component variable property within its template without explicitly stating the variable name?

Suppose my component is managing an instance of the following class: class Person { firstName: string; lastName: string; age: number; } Is there a way to directly reference its properties in the template like this: <p>{{firstName}}</p> & ...

Is it necessary to overlook Java Script when conducting load testing on my website?

We are in the process of developing a robust web application that needs to be able to handle a significant amount of traffic. I have been conducting load tests on a HP (Proliant DL 380) server with two 3.6GHz Xeon CPUs and 16GB of RAM. To perform these tes ...

Error: The function useNavigate is not recognized in react router 6

When working with react router v6 "react-router-dom": "^6.3.0", I imported the useNavigate function like so: import { useNavigate } from 'react-router-dom'; Within my function, I am using this code for navigation: { tit ...

Utilizing the Pub/Sub architecture to integrate the kafka-node library within Node Js

Utilizing the kafka-node module in my NodeJs Microservise project, I am aiming to implement a Pub/Sub (publisher and subscriber) design pattern within the Functional programming paradigm. producer.js const client = new kafka.KafkaClient({ kafkaHost: ...

Is it possible to implement mat-color in Angular's theme?

Incorporating an Angular 9 theme into my app, I encountered the need to utilize mat-color lighter and darker functions (for color and background respectively). While I have successfully implemented this in the past with a custom theme, doing so with an Ang ...

Step-by-step guide for integrating a Twig file in Symfony using Angular's ng-include feature

Seeking guidance in Angular, as a newcomer to the platform. I attempted to load a template within an ng-repeat loop like so, but encountered an error. I received the following error message: "Cross origin requests are only supported for protocol schemes ...

Using Angular's $post method to communicate with PHP CodeIgniter for making requests and handling responses

I am having trouble sending data from Angular to Codeigniter using $post. Here is the JavaScript code I am using: $scope.user.first_name = 'first name'; $scope.user.last_name = 'last name'; $http({ method: 'POST', ...

Assigning the value of one variable to be equal to the most recent state value of another variable

As a beginner in reactjs, I am facing a challenge in my code where I need to set the starting balance in a form as the closing balance of the previous record. The initial values in the form are fetched from an API call stored in the get_schedule array. The ...