I have a scenario where I have two arrays, one for categories and the other for products. Each product contains multiple categories as a comma-separated string. My goal is to match a specific category with each product's product_category value and then add the matched products to an array associated with that category.
The main objective is to link the category with the product_category field.
Below are the details of the arrays:
Products
[
{
"id": 1,
"product_title": "Product 1",
"product_size": null,
"product_author": 5,
"description": "Test Description",
"product_category": "Shirts,Pents,Salwar",
"createdAt": "2020-02-08T11:42:15.000Z",
"updatedAt": "2020-02-08T11:42:15.000Z"
},
{
"id": 4,
"product_title": "Product 2",
"product_size": null,
"product_author": 5,
"description": "Test Description",
"product_category": "Pents,Salwar",
"createdAt": "2020-02-08T11:42:15.000Z",
"updatedAt": "2020-02-10T07:08:23.000Z"
}
]
Categories
[
{
"id": 1,
"category_name": "Shirts",
"createdAt": "2020-02-08T04:59:59.000Z",
"updatedAt": "2020-02-10T06:50:05.000Z"
},
{
"id": 9,
"category_name": "Pents",
"createdAt": "2020-02-08T04:59:59.000Z",
"updatedAt": "2020-02-10T06:50:05.000Z"
}
]
Here is the code snippet that I attempted but it's not functioning as expected:
this.categories.forEach(cat => {
this.products.filter(prod => {
if (prod.product_category.split(',').indexOf(cat.category_name) !== -1) {
this.categories.push(prod);
}
});
});
I would greatly appreciate any guidance or solution to resolve this issue.