Sort Angular arrays based on JSON keys

I am currently working on building a web application using Angular that interacts with a REST-oriented server. The server sends JSON arrays (product objects) which I need to filter based on the product type field in the array. Here is a snippet of the JSON data:

{
    "name": "Water",
    "price": 0.4,
    "type": "Drinks",
    "idprod": 1,
    "description": ""
}

Product model:

export class Producte{
  name: string;
  price: number;
  type: string;
  idprod: number;

  constructor(pName: string, pPrice: number, pType: string, pIdprod: number){
    this.name = pName;
    this.price = pPrice;
    this.type = pType;
    this.idprod = pIdprod;
  }

}

Posts service:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class PostsService {

  baseUrl: string;

  constructor(private http: HttpClient) {
    this.baseUrl = 'http://134.122.51.190:8080/Project_Bar/productes';
  }

  getAll(): Promise<any[]>{
    return this.http.get<any[]>(this.baseUrl).toPromise();
  }
}

Component that retrieves all the data and stores it in an array:

import { Component, OnInit } from '@angular/core';
import { Producte } from '../../models/producte.model';
import { PostsService } from '../../services/posts.service';
@Component({
  selector: 'app-caja',
  templateUrl: './caja.component.html',
  styleUrls: ['./caja.component.css']
})
export class CajaComponent implements OnInit {
  arrPosts: any[]

  constructor(private postsService: PostsService) {
    this.arrPosts = [];
  }

  ngOnInit(): void {
    this.postsService.getAll()
    .then(posts => this.arrPosts = posts)
    .catch(error => console.log(error));
  }

}

I'm looking for a way to create separate arrays for each type of product (I have only 5 types). Any suggestions would be appreciated.

Answer №1

To efficiently organize your data, consider creating separate arrays and mapping the responses accordingly.

beverages = []
someItemArr = []

ngOnInit(): void {
this.postsService.getAll()
.then(posts.map(item => {
  if(item.type === 'Beverages') {
   this.beverages.push(item)
  } else {//perform necessary actions or checks}
)
.catch(error => console.log(error));
}

It is recommended to filter your data using database queries such as group by for faster processing. Handling it on the client side may result in longer execution times.

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

Updating array values within the httpClient method in an Angular 14 application

Having trouble updating an array value using the httpClient method. I need to figure out how to access the updated array value outside of the httpclient method. Any assistance in finding a solution would be greatly appreciated. app.component.ts: public ...

Encounter the warning message "EBADENGINE does not support engine @angulardevkit" while attempting to install class-validator and class-transformer with NestJS

Currently, I am going through the NestJS website course and I encountered an issue while trying to install class-validator and class-transformer using npm i class-validator class-transformer Upon running the command, I received the following error: npm WA ...

The query parameters and URL are failing to update properly

constructor( private router: Router, private activatedRoute: ActivatedRoute, ) {} ngOnInit() { this.activatedRoute.queryParams.subscribe(params => { //subscribe to param change console.log('params', params) } upd ...

Learn the process of marking an option as selected within an Angular component

I have an Angular component that displays a question along with a dropdown menu (<select>) to choose from various answers. My goal is to programmatically set one of the options as selected based on certain parameters present in the application' ...

"Utilizing Typescript's keyof operator on its own

I'm grappling with the challenge of creating a type that can utilize the typeof its own keys, but I'm hitting a roadblock. Below is a simplified version of what I'm attempting to achieve: type SpecialType = Record<string, (getter: <K e ...

What is causing the router.events to not fire for FooComponent in my Angular project?

Upon opening the following link , the eventsFromFoo entries in the console are nowhere to be found. It appears that this.router.events is failing to trigger for FooComponent. Any insights on why this might be happening? I am in urgent need of capturing t ...

Leverage the power of forkJoin in JavaScript by utilizing objects or sourcesObject

I'm currently facing an issue with my code snippet below: getInformations().subscribe( informations => { let subs = []; for (const information of informations) { subs.push(getOtherDetails(information.id)); } ...

Self-referencing type alias creates a circular reference

What causes the discrepancy between these two examples? type Foo = { x: Foo } and this: type Bar<A> = { x: A } type Foo = Bar<Foo> // ^^^ Type alias 'Foo' circularly references itself Aren't they supposed to have the same o ...

Accelerated repository uses TypeScript to compile a node application with dependencies managed within a shared workspace

Struggling to set up an express api within a pnpm turborepo workspace. The api relies on @my/shared as a dependency, which is a local workspace package. I have been facing challenges in getting the build process right. It seems like I need to build the s ...

Show a visual representation once a user submits a search query

I'm a beginner in Angular and web development, and I'm trying to figure out how to display an image (check sign) when the user presses enter to submit their search. My idea was to use collapse, but I'm not sure how to do it since I don' ...

What is the syntax for declaring a list of JSON objects in TypeScript?

I've been attempting to implement something similar to the following: interface IUser { addresses: JSON = []; } Unfortunately, it doesn't seem to be working! I'm looking to store a list of nested JSON objects inside the addresses field, ...

No response was forthcoming

I have been trying to send a post request to my login endpoint, but I am not receiving any response. Despite thoroughly checking my code, I am unable to figure out why there is no response being sent back. My backend is built using Express in TypeScript. B ...

Running RXJS Functions in a Sequence Maintained by an Array

I am trying to run a series of functions in sequence by storing them in an array (specifically for an Angular APP_INITIALIZER function). Here is the array in question: const obsArray = [ myService1.init(), myService2.init(), ... myServiceN ...

Utilize the power of Wikitude within an Angular 2 application

I am currently working on integrating Wikitude Architect View in Angular 2 by referring to the code at this link. My goal is to implement this code in an Angular 2 compatible way. import * as app from 'application'; import * as platform from & ...

Execute the CountUp function when the element becomes visible

Currently, I am implementing the following library: https://github.com/inorganik/ngx-countUp Is there a way to activate the counting animation only when the section of numbers is reached? In other words, can the count be triggered (<h1 [countUp]="345 ...

Experimenting with CDK overlay using Jasmine spy for testing purposes

When it comes to testing cdk overlay, what methods can be used for proper testing? Facing Challenges with MatDialog Service Unit Test in Angular 6 Here is an example of a service call: openNotifications(origin: HTMLElement) { this.refreshNotificatio ...

Can you explain the meaning of ">" in typescript?

While analyzing some code, I came across the following: let items: Array<{ name: string, value: string } | null> | null I'm curious about the significance of null> in this particular code snippet. Can you explain it to me? ...

Steps to resolve the error "Cross-Origin Request Blocked: The Same Origin Policy prohibits reading the remote resource" in a project using Angular and .NET

Whenever I make an HTTP GET request to our API endpoints, I encounter errors indicating that the CORS header 'Access-Control-Allow-Origin' is missing. Our system consists of a SQL Server database connected to a .NET API with an Angular 7 front e ...

What is the best way to utilize typed variables as types with identical names in Typescript?

Utilizing THREE.js with Typescript allows you to use identical names for types and code. For instance: import * as THREE from '/build/three.module.js' // The following line employs THREE.Scene as type and code const scene: THREE.Scene = new THRE ...

Utilizing ReactJS and TypeScript to retrieve a random value from an array

I have created a project similar to a "ToDo" list, but instead of tasks, it's a list of names. I can input a name and add it to the array, as well as delete each item. Now, I want to implement a button that randomly selects one of the names in the ar ...