i have an array of object like below. and i want to reconstruct it based on its category. and convert all subcategory into a string.
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"
}]
know i need to get result like below, with 2 elements only, category and a subcategory string separated by comma as below.
> 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 sub category is a string value here.
i did somthing like this
categories.map(key => {
sub_category.map(element => {
if (key.category == element.category) {
console.log(key.category);
console.log(element.sub_category);
}
});
});
the output was
JS: Staples
JS: Dals & Pulses
JS: Staples
JS: Ghee & Oils
JS: Staples
JS: Atta & Flours
JS: Staples
JS: Masalas & Spices
JS: Snacks and Beverages
JS: Biscuits
JS: Snacks and Beverages
JS: Chips
JS: Snacks and Beverages
JS: Namkeen & Snacks
JS: Snacks and Beverages
JS: Tea
JS: Snacks and Beverages
JS: Coffe
I'm Really confused on how to construct a new array with about about. if i try to push it in new array. i don't want category to add multiple times, if i try to push sub category into array i need to convert it to a string before push. but how any ideas is thankfulll