我正在尝试通过woocommerce API筛选带有类别的某些产品,但是这样做有点麻烦。您有正确的方法吗?谢谢
我的API数组:
{id: 199, name: "Dark Suit", slug: "dark-suit", permalink: "https://caisse.diliko.fr/produit/dark-suit/", date_created: "2020-08-20T10:53:06", …}
categories: Array(2)
0:
id: 30
name: "Clothing"
slug: "clothing"
__proto__: Object
1: {id: 31, name: "Men's Clothing", slug: "mens-clothing"}
length: 2
__proto__: Array(0)
而我的过滤功能:
export const getProductsById = (products, id) => (
products.filter(product => product.categories.name == id)
);
我想这就是您想要的。用于检查产品的任何类别是否具有您要查找的ID的过滤器。
products = [
{
id: 199,
name: "Dark Suit",
categories: [
{
id: 30,
name: "Clothing",
slug: "clothing"
},
{
id: 31,
name: "Suits",
slug: "suits"
}
]
},
{
id: 200,
name: "Light Suit",
categories: [
{
id: 30,
name: "Clothing",
slug: "clothing"
},
{
id: 31,
name: "Suits",
slug: "suits"
}
]
},
{
id: 201,
name: "Banana",
categories: [
{
id: 2,
name: "Fruit",
slug: "fruit"
},
{
id: 3,
name: "Yellow",
slug: "yellow"
}
]
},
{
id: 201,
name: "Orange",
categories: [
{
id: 2,
name: "Fruit",
slug: "fruit"
},
{
id: 4,
name: "Orange",
slug: "orange"
}
]
}
];
console.log(filter(31)); //suits
console.log(filter(2)); // fruit
console.log(filter(3)); // yellow
function filter(categoryId) {
return products.filter(product=>product.categories.some(element=>element.id==categoryId));
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句