Collect the GET parameters as an array of strings when there is only one value

How can I properly pass a string array as a parameter for a GET call?

// Passing one value
param: filters=Something
value: filters: 'Something'

// Passing multiple values
param: filters=Something&filters=Something else
value: filters: [ 'Something', 'Something else' ]

The issue arises when passing only one value in the param, as it is interpreted as a string instead of an array. On the other hand, passing more than one value results in the expected string array.

I have attempted using Array.from, but it only creates an array from the string:

['S', 'o', 'm', 'e', 't', 'h', 'i', 'n', 'g']

Is there a way to ensure that single values are recognized and processed as a String array?

Edit:

I understand the query but require filter values to accurately filter the results and return them. When there is a lone value in the filter parameter, it treats it as a string rather than an array. How can I retain a single array with a single string value in this scenario?

Answer №1

After receiving a comment from you:

You're not asking about creating the query, but how to extract a string array from the parameters even if it's just one value.

The solution involves iterating through the query string parameters and forming an array as you encounter the same parameter multiple times:

function extractParameters(query) {
  const map = new Map();
  for (const part of query.split("&")) {
    let [key, value] = part.split("=");
    key = decodeURIComponent(key); 
    value = decodeURIComponent(value);
    if (map.has(key)) {
      let current = map.get(key);
      if (Array.isArray(current)) {
        current.push(value);
      } else {
        map.set(key, [current, value]);
      }
    } else {
      map.set(key, value);
    }
  }
  return map;
}

const query1 = "filters=Something&foo=bar";
const query2 = "foo=bar&filters=Something&filters=Something%20else";

console.log("query1's params:", [...extractParameters(query1).entries()]);

console.log("query2's params:", [...extractParameters(query2).entries()]);

If you want an array every time for a specific parameter, modify the code accordingly:

const arrayParams = Object.assign(Object.create(null), {
  filters: true
});
function extractParameters(query) {
  const map = new Map();
  for (const part of query.split("&")) {
    let [key, value] = part.split("=");
    key = decodeURIComponent(key); 
    value = decodeURIComponent(value);
    if (arrayParams[key]) {
      if (map.has(key)) {
        map.get(key).push(value);
      } else {
        map.set(key, [value]);
      }
    } else {
      if (map.has(key)) {
        let current = map.get(key);
        if (Array.isArray(current)) {
          current.push(value);
        } else {
          map.set(key, [current, value]);
        }
      } else {
        map.set(key, value);
      }
    }
  }
  return map;
}

const query1 = "filters=Something&foo=bar";
const query2 = "foo=bar&filters=Something&filters=Something%20else";

console.log("query1's params:", [...extractParameters(query1).entries()]);

console.log("query2's params:", [...extractParameters(query2).entries()]);

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

Components in Angular 4 that are loaded dynamically using attribute directives are enclosed within a <div> element

My goal is to dynamically generate components based on the configuration options, specifically creating a toolbar with different "toolbar items". Following the Angular guide at: https://angular.io/docs/ts/latest/cookbook/dynamic-component-loader.html, I h ...

The parameter type 'Event' cannot be assigned to the argument type

edit-category-component.html: <custom-form-category *ngIf="model" [model]="model" (onSaveChanges)="handleChanges($event)"></custom-form-category> <mat-loader *ngIf="!model"></mat-loader> edi ...

Error: The property 'children' is not found in type '{ children?: ReactNode; }'

I have been working on implementing the search bar feature from the provided link. Despite my efforts to match the types correctly, I keep encountering a TypeScript error. Homepage.tsx const [searchQuery, setSearchQuery] = useState(query || '' ...

The name 'Queue' cannot be located in Typescript, error code ts(2304)

I'm currently trying to create a private variable of type InnerItem, but I keep encountering the following error: Error: Cannot find name 'Queue'.ts(2304) private savedItems: Queue<InnerItem> = new Queue<InnerItem>(20); Could ...

Encountering issues with `Partial<this['someProperty']>` usage in TypeScript

Provided class A { props: { bool?: boolean, test: string } = { test: 'a' }; setProps(newPropertiesr: Partial<this['props']>) { } a() { this.setProps({ bool: fals ...

The server in Angular 4 does not pause for the http call to finish before rendering. This can result in faster loading

After implementing angular universal, I was able to render the static part of HTML via server-side rendering. However, I encountered an issue where API calls were being made and the server rendered the HTML without waiting for the HTTP call to complete. As ...

Having trouble rendering a Twitter timeline on an Angular 7 project

I am attempting to embed a Twitter timeline in an Angular page by following the instructions outlined at . However, I am encountering an issue where only the button renders and not the actual timeline itself. The code in my index.html file is as follows: ...

VS Code failing to refresh TypeScript in Vue files

Currently, I'm using Vue with Vue Single File Components (SFC) and TypeScript in vscode. However, I've noticed that the types I create in a .d.ts file are not being applied or updated in my .vue files. It's only when I reload the window that ...

Form submission returns JSON data with an undefined value from the server

I've been following a tutorial here but ran into some issues due to using newer versions of Angular and Ionic. This is an excerpt from my code: createReview(review){ let headers = new HttpHeaders(); headers.append('Content-Type&apo ...

What is the best way to sort an array based on a person's name?

I have a list of different groups and their members: [ { "label": "Group A", "fields": [ { "value": "color1", "name": "Mike" }, { &quo ...

What is the best way to choose a particular radio button from a group of radio buttons using typescript?

Is there a way to automatically select a specific radio button when an item is chosen from a dropdown menu on the webpage using a TypeScript function that is triggered by the dropdown selection? ...

Increase the timestamp in Typescript by one hour

Is there a way to extend a timestamp by 1 hour? For instance, 1574620200000 (Including Microseconds) This is my date in timestamp format. How can I add a value to the timestamp to increase the time by an additional hour? ...

Issue: Unrecognized element type in next.js while starting development server

Every time I run npm run dev, I encounter the following error: Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from th ...

The art of integrating partial rendering into a template

I'm currently working on a project using Angular 2 and I need to display a partial inside a template without having to create a new component. Is this doable? import {Component} from 'angular2/core'; import {RouteConfig, ROUTER_DIRECTIVES} ...

Angular 7 - Implementing periodic JSON data retrieval from server and maintaining local storage within Angular application

Seeking guidance on how to handle updating a static json file stored in the assets directory in an Angular 7 project. The goal is to periodically fetch a json from a server, check for updates, and perform post-processing on the data in the static file (ess ...

The property 'x' is not found on 'Reel' type in this context

Creating a custom class extending Container in PIXI.js: export class CustomContainer extends Container { constructor(width: number, height: number) { super(); var sprite: Sprite = Sprite.fromImage("assets/images/elephant.png"); ...

What are some ways to control providers in targeted tests using ng-mocks?

I recently started utilizing ng-mocks to streamline my testing process. However, I am struggling to figure out how to modify the value of mock providers in nested describes/tests after MockBuilder/MockRender have already been defined. Specifically, my que ...

Populate a chart in real-time with data pulled directly from the Component

I'm completely new to Angular and I feel like I might be overlooking something important. Within my component, I have 3 variables which are populated after invoking the .subscribe method on an observable object. For example: this.interRetard = this ...

Having difficulty integrating requireJS and Node's Require in a single TypeScript project

I currently have a TypeScript project that is intended to work with both Node and the browser. In some scripts, I'm utilizing Node's require(), while in others requireJS's require(). The structure of my project directory is as follows: myPr ...

Obtain the firebase object using Angular framework

Hey there, I've been working on retrieving a Firebase object using Angular and have successfully achieved that. However, I'm now faced with the challenge of how to navigate deeper into the data that is being returned (check out the images linked ...