Mapping URLs to objects in JavaScript, TypeScript, and Angular4

I have implemented a class called SearchFilter

class SearchFilter { 
   constructor(bucket: string,
               pin: number,
               qty: number,
               category: string) {
   }
}

When the user performs a search, I populate the filter into matrix params.

router.navigate(['filter', searchFilter]); //searchFilter is an instance

The resulting URL structure is as follows:

filter;bucket=MPC123;category=JOINT;qty=90;pin=9087

This functionality is utilized in another component where the parameter is mapped back to an Object of type SearchFilter. However, it is necessary to set the data types explicitly in this process.

   const params = this.activatedRoute.snapshot.params;
   const filter = this.getFilterFromParams(params);

   getFilterFromParams(params) :SearchFilter {
      const filter = new SearchFilter();
      Object.keys(params).forEach((key) => {
         switch(key) {
             case 'pin':
             case 'qty': filter[key] = Number(params[key]); break;
             default: filter[key] = params[key];
         }
      });
      return filter;
   }

Looking at the code above, a custom mapping function is used to map the parameters back to an Object. Is there a more straightforward way to achieve this or is this a commonly used pattern?

I need to rely on URLs for user-friendliness, as users should be able to share URLs with different filters.

Answer №1

To implement a static factory method, we can follow this example:

class FilterFactory {
  constructor(bucket: string, pin: number, qty: number, category: string) {
    // Constructor logic here
  }

  public static createFilter({ bucket, pin, qty, category }) {
    // Validate that pin and qty are integers before creating the filter object
    return new FilterFactory(
      bucket,
      parseInt(pin),
      parseInt(qty),
      category
    );
  }
}

We can then utilize the factory method as shown below:

const sampleParams = {
  bucket: "ABC456",
  category: "XYZ",
  qty: "75",
  pin: "3456"
};

const customFilter = FilterFactory.createFilter(sampleParams);

Answer №2

Consider utilizing the functionalities of Object.assign and the spread syntax:

createSearchFilterFromParams(params) : SearchFilter {
    return Object.assign(new SearchFilter(), params,
        ...['tag', 'quantity'].map(key => key in params && { [key]: Number(params[key]) })
    );
}

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 do I use props to enable and conceal elements like lists, buttons, and images?

Check out this unique component: <ReusedHeader H1headerGray="text here... " H2headerRed="text2 here ! " pheader="p1" getStarted="button text1" hrefab="button url 1" whatWeDo="button text ...

The browser message states: Variable $? Not Found

As a newcomer to javascript (jquery/json), I've created code to display a chart using CanvasJS with a php/json data fetching script. However, I'm facing an issue where the chart is not rendering when I integrate my code. Upon inspecting the brows ...

The sequence of Angular directives being executed

When multiple directives are applied to an element in AngularJS, what determines the order in which they will be executed? For instance: <input ng-change='foo()' data-number-formatter></input> Which directive, the number formatter ...

I'm wondering if there exists a method to arrange a multi-array in javascript, say with column 1 arranged in ascending order and column 2 arranged in descending order?

Here is an example of a randomly sorted multi-array: let arr = [[3, "C"], [2, "B"], [3, "Q"], [1, "A"], [2, "P"], [1, "O"]]; The goal is to sort it in the following order: arr = [[1, "O" ...

Select from a variety of backgrounds using the dropdown menu on the site

I seem to be struggling with javascript and php, but I know that in order to make this function properly, I need to utilize both languages. My goal is to set up a "select box" featuring 4 different images. There will be a default image displayed, but user ...

Saving base64 encoded pdf on Safari

I am facing an issue with a POST call that returns a base64 PDF. The problem arises when trying to convert it to a Blob and download it using Safari browser. This method works perfectly in all other browsers. openPdf = () => { const sendObj = { ...

Exporting NativeModules for npm package in React Native

I'm attempting to convert my React Native App into a node module. The issue I'm facing is that the module consists mainly of a NativeModule. Thus, my index.js file appears like this: import { NativeModules } from 'react-native'; expo ...

What could be causing my data to undergo alterations when transitioning from a frontend form submission to a backend API?

In my experience with Next.js 13 and Prisma, I encountered a peculiar issue. I had set up a basic form to collect user information for an api request. Oddly enough, when I printed the data right before sending it, everything seemed fine. However, upon arri ...

"Encountering a problem when trying to display Swagger-Editor for the second

While integrating the swagger-editor package into my React application, I encountered an issue. The first time I fetch the Swagger specifications from GitHub, everything works perfectly and validates correctly. However, upon rendering it a second time, an ...

Nextjs optimizing page caching to reduce unnecessary rendering

Within my Next.js application, I have implemented two unique pages. Each page is designed to display a randomly selected person's name when the component is initially loaded. simpsons.tsx export default function Simpsons() { const [person, setPerso ...

Retrieve JSON object by matching another JSON property

I am working with an array of id's and their respective contents in a JSON response. My goal is to retrieve the content based on the received id. For instance, if the ID is 1 (returned from the JSON), I aim to access the JSON data using "data.id" (wh ...

The function for executing the specific command is not recognized and is resulting in a TypeError: client.commands

I'm having an issue with the code below and need a solution. Please help. Error : TypeError: client.commands.get(…).execute is not a function I am encountering difficulty with this specific command in my code: client.command ...

Function activation in Element requires a double click to initiate

I've encountered an issue with a web element I'm working on where the click function only triggers after the first click, rendering the initial click ineffective. Here's the code snippet in question: HTML: <div> <a href="#0" cla ...

What is the best way to create a gradual color change in each individual cell instead of changing all at once?

Looking for some help with a grid I'm working on. I've got the cells changing colors like I want them to, but they're all changing at once. What I really need is for them to light up in a specific order - Yellow, Green, Blue, White, Orange. ...

Discover the magic of observing prop changes in Vue Composition API / Vue 3!

Exploring the Vue Composition API RFC Reference site, it's easy to find various uses of the watch module, but there is a lack of examples on how to watch component props. This crucial information is not highlighted on the main page of Vue Composition ...

What is the best way to incorporate one Div within another Div using JavaScript?

I have a single main div with an id, and I am looking to insert 4 additional child divs inside it. Each of these child divs will then contain 5 more divs each. The code snippet that I currently have is as follows: $( document ).ready(function() { for( ...

The setting `ensureCleanSession: true` doesn't appear to be effective when included in the capabilities for Internet Explorer 11

Currently, I am testing a login/logout application with the help of protractor. One challenge I am facing is dealing with a popup that appears after each login/logout scenario. In order to ensure the popup appears after each login, I need to reset the IE ...

Struggling to grasp how to implement Redux and React-router together in one component

I have recently embarked on learning TypeScript and encountered a confusing behavior. Upon encountering this error: Type 'ComponentClass<{}>' is not assignable to type 'StatelessComponent<void | RouteComponentProps<any>> ...

Checking radios or checkboxes will always result in a null value when retrieving their form values

After following the instructions in the Angular 2 cookbook for dynamic forms, I encountered an issue with the radios and checkboxes. Despite checking them, they always return a null value. Interestingly, the touched properties of the radios and checkboxes ...

Decode my location and input the address before validating it

While I have come across numerous plugins that enable geolocation and display it on a map, I am searching for something unique. I am interested in implementing geocoding when a user visits the page with an option to "allow geolocation." If the user agrees ...