Search code examples
javascriptangularstringtypescriptangular-httpclient

Concatenate query params and add them to url


I have a checkbox of 4 categories (Error, Warning, Info and Debug) and whenever the user check some of them, I have to add them to the query to make an httpclient call.

For example if the user check all of them I should send a query with: (category=eq=Error,category=eq=Warning,category=eq=Info,category=eq=Debug)

That's what I did , I tried to create a string object and concatenate one by one if they are checked :

 if (obj.category) {
      const ctgLength = obj.category.length; //the number of categorieschecked 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] + ")";
   }

But what I get is: (category=eq=Error,category=eq=Info,category=eq=Debug) The for loop affect only the value of the last iteration.

First: is what I'm doing a good way to generate a query in my case ? Second: How can I fix this code to get all the categories in the query ?

Thanks.


Solution

  • wouldn't something like this work?

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

    Edit: as @Mkdgs mentioned, we can also use toString() instead of join as it adds comma by default

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