Guide to encoding an array of objects into a URI-friendly query string using TypeScript

Just getting started with typescript and looking for some help. I have an input array structured like this:

filter = [
  {
    field : "eventId",
    value : "123"
  },
  {
    field : "baseLocation",
    value : "singapore"
  }
]

The desired format for this array of objects is as follows:

..test.com?search=eventid%20eq%20123&search=baselocation%20eq%20singapore

I attempted the following code but it didn't yield any results:

    var test = '';

    if (filter != undefined && filter.length > 0)
      filter.forEach(item => {
        test += Object.keys(item).map(k => `${k}=${encodeURIComponent(item[k])}`);
      });

    console.log(test);

Every time I check the console log, it's empty. Is there a better approach to achieve this?

Please keep in mind that I require all field values to be in lowercase instead of camelcase. Any guidance on how to accomplish this would be greatly appreciated.

Answer №1

The issue with the filter.array.forEach statement is that it tries to call forEach on an undefined property, leading to a crash. Additionally, some necessary formatting components like the %20eq%20 substrings and lowercasing are missing.

To address this problem, here's an alternative solution using array.map to generate the expected output by directly accessing the object properties:

const filter = [
  {
    field : "eventId",
    value : "123"
  },
  {
    field : "baseLocation",
    value : "singapore"
  }
];

const expected = `..test.com?search=eventid%20eq%20123&search=baselocation%20eq%20singapore`;

const actual = `..test.com?${filter.map(o =>
  `search=${o.field}%20eq%20${o.value}`
).join`&`.toLowerCase()}`;

console.log(actual === expected, actual);

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

How can I properly customize and expand upon a Material UI ListItem component?

I'm currently working with TypeScript version 3.4.5 and Material UI version 4.2. I have the following code snippet: interface MyItemProps { name: string; value: string; } function Item({ name, value, ...props }: ListItemProps<'li&apo ...

Encountering an issue with setting up MikroORM with PostgreSQL due to a type

I'm currently working on setting up MikroORM with PostgreSQL, but I've encountered a strange error related to the type: Here is the code snippet: import { MikroORM, Options} from "@mikro-orm/core"; import { _prod_ } from "./consta ...

Performing unit testing on a Vue component that relies on external dependencies

Currently, I am in the process of testing my SiWizard component, which relies on external dependencies from the syncfusion library. The component imports various modules from this library. SiWizard.vue Imports import SiFooter from "@/components/subCompon ...

Create a combined string from a structure resembling a tree

In my web application, I have a type that defines the different routes available: interface IRoute { readonly path: string, readonly children?: IRoute[] } I want to create a union type containing all possible paths based on an IRoute object. Let&apos ...

Exploring the differences between Angular's @Input and @Output directives and utilizing Injectable Services

When considering the differences between @Input/@Output in parent and child components versus using services that are instantiated only once with dependency injection (@Injectable()), I find myself questioning whether there are any distinctions beyond the ...

Unable to simulate axios instance in a Typescript environment

After reading through this particular article, I decided to attempt writing a unit test while simulating Axios (with Typescript). Incorporating an Axios instance to define the baseUrl. // src/infrastructure/axios-firebase.ts import axios from 'axios ...

Error encountered when transitioning to TypeScript: Unable to resolve '@/styles/globals.css'

While experimenting with the boilerplate template, I encountered an unusual issue when attempting to use TypeScript with the default NextJS configuration. The problem arose when changing the file extension from .js to .tsx / .tsx. Various versions of NextJ ...

Mapping a JSON array within a static method in Angular2 and TypeScript

Struggling with the syntax to properly map my incoming data in a static method. The structure of my json Array is as follows: [ { "documents": [ { "title": "+1 (film)", "is-saved": false, ...

sort the array based on its data type

Recently diving into typescript... I have an array that is a union of typeA[] | typeB[] but I am looking to filter based on the object's type interface TypeA { attribute1: string attribute2: string } interface TypeB { attribute3: string attri ...

Encountering the issue of receiving "undefined" when utilizing the http .get() method for the first time in Angular 2

When working in Angular, I am attempting to extract data from an endpoint. Below is the service code: export class VideosService { result; constructor(private http: Http, public router: Router) { } getVideos() { this.http.get('http://local ...

Using Typescript to pass an optional parameter in a function

In my request function, I have the ability to accept a parameter for filtering, which is optional. An example of passing something to my function would be: myFunc({id: 123}) Within the function itself, I've implemented this constructor: const myFunc ...

Next.js TypeScript throws an error stating that the object 'window' is not defined

When trying to declare an audio context, I encountered an error stating that window is undefined. I attempted declaring declare const window :any above window.Context, but the issue persists. Does anyone have a solution for this problem? window.AudioCont ...

Merging Promises in Typescript

In summary, my question is whether using a union type inside and outside of generics creates a different type. As I develop an API server with Express and TypeScript, I have created a wrapper function to handle the return type formation. This wrapper fun ...

Tips on Configuring the Attributes of a TypeScript Object in Angular 2

A TypeScript class called Atom is defined as follows: export class Atom { public text: String; public image: boolean; public equation: boolean; } To create an object of type Atom class and set its properties, the following steps are used: atom: ...

Can an L1 VPC (CfnVpc) be transformed into an L2 VPC (IVpc)?

Due to the significant limitations of the Vpc construct, our team had to make a switch in our code to utilize CfnVpc in order to avoid having to dismantle the VPC every time we add or remove subnets. This transition has brought about various challenges... ...

ReactJS Provider not passing props to Consumer resulting in undefined value upon access

Hey there! I've been facing an issue with passing context from a Provider to a consumer in my application. Everything was working fine until suddenly it stopped. Let me walk you through a sample of my code. First off, I have a file named AppContext.t ...

Experimenting with Date Object in Jest using Typescript and i18next

I have included a localization library and within my component, there is a date object defined like this: getDate = () => { const { t } = this.props; return new Date().toLocaleString(t('locale.name'), { weekday: "long", ...

Modify visibility within a subclass

Is there a way to modify property visibility in a child class from protected to public? Consider the following code snippet: class BaseFoo { protected foo; } class Foo extends BaseFoo { foo = 1; } new Foo().foo; It seems that this change is pos ...

In order to conceal the div tag once the animation concludes, I seek to implement React

I'm currently using the framer-motion library to add animation effects to my web page. I have a specific requirement where I want to hide a div tag used for animations once the animation is complete. Currently, after the animation finishes, the div t ...

Please input the number backwards into the designated text field

In my react-native application, I have a TextInput where I need to enter numbers in a specific order such as 0.00 => 0.01 => 0.12 => 1.23 => 12.34 => 123.45 and so on with each text change. I tried using CSS Direction "rtl" but it didn't work as expec ...