Filter Angular arrays by json fields

Context: I'm trying to develope a web application in angular that works with a rest-oriented server, I recieve json arrays from the server (product objects) and I would like to filter them by the type of the product which is in a field of the array. Sample of the json:

{
    "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 takes all the data and puts 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));
  }

}

My question is how I can create different arrays for every type of product(I have only 5 types). Thanks.

Upvotes: 0

Views: 77

Answers (1)

Arams
Arams

Reputation: 199

You can create different arrays you need. and map your response.

drinks = []
someProductArr = []

ngOnInit(): void {
this.postsService.getAll()
.then(posts.map(item => {
  if(item.type === 'Drinks') {
   this.drinks.push(item)
  } else {//do or check what you need}
)
.catch(error => console.log(error));
}

But better filter your data with database request(something like group by). On client side it will take longer

Upvotes: 2

Related Questions