给出以下数据:
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 : " "
},
]
答案 0 :(得分:0)
方法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 ,这为您提供了各种各样的功能。