I’m trying to filter some products with the categories (by the woocommerce API) but i have a little trouble to do it. do you have the right way to do it? thanks
My array from the API :
JavaScript
x
10
10
1
{id: 199, name: "Dark Suit", slug: "dark-suit", permalink: "https://caisse.diliko.fr/produit/dark-suit/", date_created: "2020-08-20T10:53:06", …}
2
categories: Array(2)
3
0:
4
id: 30
5
name: "Clothing"
6
slug: "clothing"
7
__proto__: Object
8
1: {id: 31, name: "Men's Clothing", slug: "mens-clothing"}
9
length: 2
10
__proto__: Array(0)
And my filter function:
JavaScript
1
4
1
export const getProductsById = (products, id) => (
2
3
products.filter(product => product.categories.name == id)
4
);
Advertisement
Answer
Here’s what you want, I reckon. A filter that checks whether any of the categories of the product has the id you’re looking for.
JavaScript
1
75
75
1
products = [
2
{
3
id: 199,
4
name: "Dark Suit",
5
categories: [
6
{
7
id: 30,
8
name: "Clothing",
9
slug: "clothing"
10
},
11
{
12
id: 31,
13
name: "Suits",
14
slug: "suits"
15
}
16
]
17
},
18
{
19
id: 200,
20
name: "Light Suit",
21
categories: [
22
{
23
id: 30,
24
name: "Clothing",
25
slug: "clothing"
26
},
27
{
28
id: 31,
29
name: "Suits",
30
slug: "suits"
31
}
32
]
33
},
34
{
35
id: 201,
36
name: "Banana",
37
categories: [
38
{
39
id: 2,
40
name: "Fruit",
41
slug: "fruit"
42
},
43
{
44
id: 3,
45
name: "Yellow",
46
slug: "yellow"
47
}
48
]
49
},
50
{
51
id: 201,
52
name: "Orange",
53
categories: [
54
{
55
id: 2,
56
name: "Fruit",
57
slug: "fruit"
58
},
59
{
60
id: 4,
61
name: "Orange",
62
slug: "orange"
63
}
64
]
65
}
66
67
];
68
69
console.log(filter(31)); //suits
70
console.log(filter(2)); // fruit
71
console.log(filter(3)); // yellow
72
73
function filter(categoryId) {
74
return products.filter(product=>product.categories.some(element=>element.id==categoryId));
75
}