In my array of objects, I need to reorganize it based on categories and convert all subcategories into strings.
var main = [{
"id": "1",
"category": "Staples",
"sub_category": "Dals & Pulses"
}, {
"id": "2",
"category": "Staples",
"sub_category": "Ghee & Oils"
}, {
"id": "3",
"category": "Staples",
"sub_category": "Atta & Flours"
}, {
"id": "4",
"category": "Staples",
"sub_category": "Masalas & Spices"
}, {
"id": "5",
"category": "Snacks and Beverages",
"sub_category": "Biscuits"
}, {
"id": "6",
"category": "Snacks and Beverages",
"sub_category": "Chips"
}, {
"id": "7",
"category": "Snacks and Beverages",
"sub_category": "Namkeen & Snacks"
}, {
"id": "8",
"category": "Snacks and Beverages",
"sub_category": "Tea"
}]
I want to transform this data into the expected output below, with each category and its corresponding subcategories separated by commas:
> EXPECTED OUTPUT:-
var result = [
{
category: 'Staples',
sub_cat: 'Dals & Pulses, Ghee & Oils, Atta & Flours, Masalas & Spices' },
{
category: 'Snacks and Beverages',
sub_cat: 'Biscuits, Chips, Namkeen & Snacks, Tea'
}],
The subcategory values are string here.
This is what I have tried so far:
categories.map(key => {
sub_category.map(element => {
if (key.category == element.category) {
console.log(key.category);
console.log(element.sub_category);
}
});
});
However, the output was not as expected. I am struggling to construct a new array with the desired structure. Any ideas or suggestions would be greatly appreciated.