Converting an array into an object in Angular for query parameters

In my Angular 12 application, I have an array of objects that I need to convert into query parameters in order to route to a generated URL. The desired query parameters should look like this:

Brand:ABC:Brand:XYZ:Size:13x18:Size:51x49x85

[{
 "values": ["ABC", "XYZ"],
 "show": true,
 "label": "Brand",
 }, {
 "values": ["13 x 18", "51x49x85"],
 "show": true,
 "label": "Size",
}]

I attempted to achieve this but the result was not as expected.

params = new HttpParams({fromObject: { r: myArray }})

Is there something that I am missing?

Answer №1

As pointed out in the comment, your query string is incorrect. It should be:

Brand=ABC&Brand=XYZ&Size=13%20x%2018&Size=51x49x85

Also, keep in mind that HttpParamsOptions.fromObject does not support arrays.

To properly form the query string, you will need to loop through the array elements.

  1. Loop through each object in the myArray.

  2. Iterate over each element in the values array, combine it with the key (label), and encode the value. Then concatenate each element with &.

  3. Concatenate each element with &.

let myArray = [{
    "values": ["ABC", "XYZ"],
    "show": true,
    "label": "Brand",
}, {
    "values": ["13 x 18", "51x49x85"],
    "show": true,
    "label": "Size",
}];

let queryString = myArray.map(x => x.values.map(y => `${x.label}=${encodeURI(y)}`).join('&'))
    .join('&');


console.log(queryString);

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

Resolve an "Uncaught ReferenceError" by importing an unused component to fix the error of not being able to access a variable before initialization

In my service file, where I store all other services used in the frontend, there is an import section that includes one component even though it is not being used. import { VacationComponent } from 'app/view/vacation/vacation.component'; When I ...

The Karma tool is throwing a TypeError because it is unable to access the 'length' property of a null value

Despite reviewing numerous inquiries regarding this error, none have provided insight into identifying the root cause of the issue. How can I pinpoint the origin of this error and what steps can I take to resolve it? TypeError: Cannot read property ' ...

Angular: Issue with subscribed variable visibility on screen

I am currently developing user management functionality. When a button is clicked, the goal is to save a new user and display an incoming password stored in the system. Below is a snippet of my code: onClick() { /*Code to populate the newUser variable from ...

Error Handler: Unable to retrieve the error object when utilized with a promise

I'm currently working on an angular application with a custom error handler implementation. One interesting point to note is that when you have a custom error handler and use an observable with http without catching errors using a catch block, like i ...

What type of HTML tag does the MUI Autocomplete represent?

Having trouble calling a function to handle the onchange event on an autocomplete MUI element. I've tried using `e: React.ChangeEvent`, but I can't seem to locate the element for the autocomplete component as it throws this error: The type &apos ...

Discover how to set up lazy loaded child routes within a parent route that is also loaded lazily in Angular 2

Struggling to implement lazy loading for my app has been a series of challenges. I successfully implemented lazy loading for the main route, /admin, but now I am facing issues while adding another route, /admin/login. This is what I tried: admin-router.m ...

Separate the generic function interface into its own type/interface variable

Below is an example of TypeScript generics that I found on typescriptlang. function getProperty<Type, Key extends keyof Type>(obj: Type, key: Key) { return obj[key]; } let x = { a: 1, b: 2, c: 3, d: 4 }; getProperty(x, "a"); getProperty ...

"Troubleshooting: Module not found" (Getting started with Jest in a nested project connected to a shared directory)

I've recently taken over a project that contains the following folder structure: node_modules/ server/ ├── node_modules/ ├── src/ │ └── helpers/ │ ├── updateTransactions.ts │ └── updateTransactions.tes ...

Adjust the size of the labels on a grouped bar chart using Angular Chartjs

I just started working with Angular and Chart.js, and I have the following code for my bar chart: const chart = new Chart(this.ctx, { type: 'bar', data: { labels: labels, datasets: [{ label: 'Success Prediction Count', ...

Delete a particular item from a JSON object in real-time using TypeScript/JavaScript

Upon examining the JSON data provided, it contains a node called careerLevels which includes inner child elements. input = { "careerLevelGroups": [ { "201801": 58, "201802": 74, ...

The observer error silently assumes an undefined type

Currently, I am attempting to implement the guidance provided in this Stack Overflow post on performing a File Upload using AngularJS 2 and ASP.net MVC Web API. The issue arises from the upload.service.ts file where an error is identified next to the prob ...

What are the appropriate scenarios to utilize the declare keyword in TypeScript?

What is the necessity of using declare in TypeScript for declaring variables and functions, and when is it not required? For instance, why use declare var foo: number; when let foo: number; seems to achieve the same result (declaring a variable named ...

Tips for organizing your CSS from scratch without relying on a pre-existing framework such as bootstrap, bulma, or materialize

As I embark on a new Angular project, the decision has been made to create our own component library instead of using frameworks like Bootstrap, Bulma, or Materialize. Despite some initial research, I'm feeling a bit lost on where to begin (other than ...

After clicking on the "Delete Rows" button in the table, a white color suddenly fills the background in Angular Material

When the dialog box pops up, you'll see a white background color: https://i.stack.imgur.com/EflOx.png The TypeScript code for this action can be found in config-referrals.component.ts openDialog(action, obj) { this.globalService.configA ...

Can a custom type guard be created to check if an array is empty?

There are various methods for creating a type guard to ensure that an array is not empty. An example of this can be found here, which works well when using noUncheckedIndexedAccess: type Indices<L extends number, T extends number[] = []> = T["le ...

What is the best way to tally up the occurrences of a specific class within an Angular application?

After reviewing the resources provided below on impure and pure pipes in Angular applications: What is impure pipe in Angular? I have been curious about inspecting the instances created by an Angular application firsthand, although I am uncertain if thi ...

Getting the route parameter in Angular 2 is easy with the stable router

Currently working with the latest stable Angular 2 RC version. Unfortunately, the documentation for the new router component has yet to be completed. Struggling to retrieve a parameter from a navigated page. Defined routes: @Routes([ {path: '/resu ...

Angular: Keeping all FormControls in sync with model updates

I am dealing with a collection of FormControls that were created using FormBuilder: this.someForm = this.fb.group({ name: '', size: '', price: '', }); Is there an alternative method to update them based on ...

transmit information to a service using Angular 8

There are 4 multiselect dropdowns, and when I click on an event, I save the data array of objects in the same component. Now, I need to send this data to display it in another component. To achieve this, I am using a service. However, every time I send th ...

Puppeteer: What is the best way to interact with a button that has a specific label?

When trying to click on a button with a specific label, I use the following code: const button = await this.page.$$eval('button', (elms: Element[], label: string) => { const el: Element = elms.find((el: Element) => el.textContent === l ...