如何使用离子框架过滤此JSON数据



给定以下数据:

products = [
  {
    id : "123",
    price : "10.5",
    quantity : 1,
    category1 : "Catagort-1",
    category2 : " ",
    category3 : " "
  },
  {
    id : "133",
    price : "10.5",
    quantity : 1,
    category1 : " ",
    category2 : " ",
    category3 : "Catagory-3"
  },
  {
    id : "144",
    price : "7.00",
    quantity : 1,
    category1 : "Catagort-1",
    category2 : " ",
    category3 : " "
  },
  {
    id : "155",
    price : "11.5",
    quantity : 1,
    category1 : "",
    category2 : "Catagory-2",
    category3 : ""
  },
  {
    id : "166",
    price : "9.00",
    quantity : 1,
    category1 : " ",
    category2 : " ",
    category3 : "Catagory-3"
  },
  {
    id : "177",
    price : "8.5",
    quantity : 1,
    category1 : "",
    category2 : "Catagory-2",
    category3 : ""
  }
];

我想像这样过滤上面的数据:

  • 给定三个数组:cat1[]cat2[]cat3[] ;
  • 将具有 category1 属性值的所有数据存储到 cat1 数组中。

例如:

cat1= [
 {
        id : "123",
        price : "10.5",
        quantity : 1,
        category1 : "Catagort-1",
        category2 : " ",
        category3 : " "
      },
 {
        id : "144",
        price : "7.00",
        quantity : 1,
        category1 : "Catagort-1",
        category2 : " ",
        category3 : " "
      },
]

方法 1

this.products.forEach(res=>{
  if(res.category1=='Catagory-1'){
    this.cat1.push(res);
  }
  else if(res.category2 == 'Catagory-2'){
    this.cat2.push(res);
  }else if(res.category3 == 'Catagory-3'){
    this.cat3.push(res);
  }
})

方法 2

    this.cat1 = this.products.filter(res=>{
      return res.category1 == 'Catagory-1'
    });
    this.cat2 = this.products.filter(res=>{
      return res.category2 == 'Catagory-2'
    })
    this.cat3 = this.products.filter(res=>{
      return res.category3 == 'Catagory-3'
    });

此外,您可以查看此库 https://lodash.com/docs/4.17.11,这为您提供了各种各样的功能。

最新更新