首页 > 解决方案 > 在角度 8 中应用多个过滤器并对 api 响应进行排序

问题描述

在收到我的 api 响应后:

[
    {
      "imgPaths":[
         "gallery/products/55ccb60cddb4d9bded02accb26827ce4"
      ],
      "_id":"5f3e961d65c6d591ba04f3d3",
      "productName":" Jiva Ayurveda Honey (500g) ",
      "categoryId":{
         "_id":"5f2139322d46a455487b2ea6",
         "categoryName":"Nutrition and supplements",
         "imgPath":"gallery/category/c20ae1717899fad2a6ff3f3ceab381ff"
      },
      "manufacturer":"Jiva",
      "basePrice":"190",
      "finalPrice":"187",
      "availability":"in-stock",
      "createdAt":"2020-08-20T15:26:21.092Z"
   },
   {
      "imgPaths":[
         "gallery/products/72b0e1cf078f26ed0ec0280c1cf8865d"
      ],
      "_id":"5f3e962465c6d591ba04f3d4",
      "productName":"Baidyanath Keshrikalp Royal Chyawanprash (500g) ",
      "categoryId":{
         "_id":"5f2139322d46a455487b2ea6",
         "categoryName":"Nutrition and supplements",
         "imgPath":"gallery/category/c20ae1717899fad2a6ff3f3ceab381ff"
      },
      "manufacturer":"Baidyanath",
      "basePrice":"394",
      "finalPrice":"378",
      "availability":"in-stock",
      "createdAt":"2020-08-20T15:26:28.103Z"
   }
]

我想执行“制造商”和“最终价格”的过滤器以及“从高到低”、“从低到高”和“最近添加”等不同的排序,为此我写下了以下方法:

  1. 对于排序,我喜欢如下:
    onSortChange(event) {
        //why not lodash used : accepting values are in string formats
        if(event.value==="Lowtohigh"){
          this.productsbycategory.sort((a, b) => {
                return Number(a.finalPrice) - Number(b.finalPrice); 
           })
          }
          else if(event.value==="hightolow"){
            this.productsbycategory.sort((a, b) => {
              return Number(b.finalPrice) - Number(a.finalPrice);
            })
           }
          else if(event.value==="recentlyadded"){
            this.productsbycategory.sort((a, b) => {
              return +new Date(b.createdAt) - +new Date(a .createdAt);
            })
        }
    }
  1. 对于过滤制造商,我写的方法如下:

onBrandFilterChange(事件) {

  if(event.target.checked===true && !numbers.includes(event.target.value)){
    numbers.push(event.target.value);
    this.productsbycategory= _.filter(this.filteredProducts, function(p){
      return _.includes(numbers, p.manufacturer);
    });
  }
  else if(event.target.checked===false && numbers.includes(event.target.value)){
    _.pull(numbers,event.target.value);
    if(numbers.length>0){
    this.productsbycategory= _.filter(this.filteredProducts, function(p){
      return _.includes(numbers, p.manufacturer);
    });
    }
    else{
        this.setData();
    }
  }
}
  1. 对于过滤价格我写的方法如下:
onPriceFilterChange(min, max) {
    console.log(min, max);
    if (min >= 1 && max <= 5000) {
      this.productsbycategory = this.productsbycategory.filter(function (elem) {
        return Number(elem.finalPrice) >= min && Number(elem.finalPrice) <= max;
      });
    } else {
      alert('Please select valid range');
    }
  }


我想修改上面的代码,以便我们可以一次执行所有过滤器和排序。}

标签: javascriptangulartypescript

解决方案


检查这种方法。阅读代码中的注释,按“运行代码片段”按钮对其进行测试

// Your data
data = [
    {
      "imgPaths":[
         "gallery/products/55ccb60cddb4d9bded02accb26827ce4"
      ],
      "_id":"5f3e961d65c6d591ba04f3d3",
      "productName":" Jiva Ayurveda Honey (500g) ",
      "categoryId":{
         "_id":"5f2139322d46a455487b2ea6",
         "categoryName":"Nutrition and supplements",
         "imgPath":"gallery/category/c20ae1717899fad2a6ff3f3ceab381ff"
      },
      "manufacturer":"Jiva",
      "basePrice":"190",
      "finalPrice":"187",
      "availability":"in-stock",
      "createdAt":"2020-08-20T15:26:21.092Z"
   },
   {
      "imgPaths":[
         "gallery/products/72b0e1cf078f26ed0ec0280c1cf8865d"
      ],
      "_id":"5f3e962465c6d591ba04f3d4",
      "productName":"Baidyanath Keshrikalp Royal Chyawanprash (500g) ",
      "categoryId":{
         "_id":"5f2139322d46a455487b2ea6",
         "categoryName":"Nutrition and supplements",
         "imgPath":"gallery/category/c20ae1717899fad2a6ff3f3ceab381ff"
      },
      "manufacturer":"Baidyanath",
      "basePrice":"394",
      "finalPrice":"378",
      "availability":"in-stock",
      "createdAt":"2020-08-20T15:26:28.103Z"
   }
];

// Price filter function
// Provide data array, min and max price
const priceFilter = (data, min, max) => data.filter((item) => item.finalPrice >= min && item.finalPrice <= max);

// Manufacture filter function
// Provide name
const manFilter = (data, man) => data.filter((item) => item.manufacturer.toLowerCase() === man.toLowerCase());

// Sort data array by some parameters
// Provide data array and options object:
// desc:true for descending sort (ascending
// by default), price:true to sort by price
// or date:true to sort by date.
const customSort = (data, { desc, price, date }) => data.sort((a, b) => {
  if(desc) { const c = a; a = b; b = c; }
  if(price) return a.finalPrice - b.finalPrice;
  else if(date) return new Date(a.createdAt) - new Date(b.createdAt);
});

// Test

// Descending sort by date
console.log('Sort test: ', customSort(data, { desc: true, date: true }));

// Filter by price
console.log('Filter by price test: ', priceFilter(data, 200, 400));

// Filter by name (case insensetive)
console.log('Filter by name test: ', manFilter(data, 'JIVA'));

如果您想一个一个地应用多个过滤器,那么就这么简单

// data = [ ... your data here ... ];

// First filter your data by manufacturer
data = manFilter(data, 'Baidyanath');

// Now take previously filtered data
// and filter again by price limits
data = priceFilter(data, 100, 300);

// Now take previously filtered data
// by manufacturer and price limits
// and do ascending sort by price field
data = customSort(data, { price: true });

// Now your data is filtered and sorted
// Continue to your program logic
return data;

推荐阅读