Home > Blockchain >  How to filter and group data into 2 categories (class variables)?
How to filter and group data into 2 categories (class variables)?

Time:10-13

So I have this method:

getProducts() {
this.productService.getProducts().subscribe(products => {
  this.products = products;
});

Everything works great, so these are the 'products':

  • 0: {code: 'Product1', order: 1, description: 'Description', category: 'categoryone', price: 1500, …}
  • 1: {code: 'Product1', order: 2, description: 'Description', category: 'categoryone', price: 1000, …}
  • 2: {code: 'Product2', order: 1, description: '', category: 'categorytwo', price: 1199, …}
  • 3: {code: 'Product2', order: 2, description: '', category: 'categorytwo', price: 2999, …}
  • 4: {code: 'Product2', order: 3, description: '', category: 'categorytwo', price: 7999, …}

So what I'm trying is to filter and group that products into two class variables, for example categoryOne and categoryTwo and then display that data, but I don't know how.

CodePudding user response:

If you know the category names and products is an array you can just loop over the array and use if conditions to assign the product to their respective variables

categoryoneProducts = []
categorytwoProducts = []

getProducts() {
  this.productService.getProducts().subscribe(products => {
    this.products = products;

    this.categoryoneProducts = []
    this.categorytwoProducts = []

    this.products.forEach(product => {

      if (product.category === 'categoryone') {
        categoryoneProducts.push(product)
      } else if (product.category === 'categorytwo') {
        categorytwoProducts.push(product)
      }
    })
  });
}
  • Related