Reputation: 472
I've got a collection of objects with the following format:
{
{
"articleId": "a0sf1000004najmAAA",
"articleName": "A value for name",
"footnote": "",
"mainCat": "A Category 1",
"subCat": "A SubCategory 1",
}, {
"articleId": "a0sf1000004najmAAA",
"articleName": "A value for name",
"footnote": "",
"mainCat": "A Category 1",
"subCat": "A SubCategory 2",
},
}
After reduction and grouping I would like to have the following:
{
"A Category 1": {
"A SubCategory 1": {
{
some items belonging to SubCat 1 and Cat 1
}
},
"A SubCategory 2": {
{
some items belonging to SubCat 2 and Cat 1
}
}
}
}
For now, I'm able to return all my single article grouped by sub-category, but how can I group my sub-categories by their main category?
var catalog = data;
var groupBySubCat = catalog.reduce(function(obj, item) {
obj[item.subCat] = obj[item.subCat] || [];
obj[item.subCat].push(item);
return obj;
}, {});
var groups = Object.keys(groupBySubCat).map(function(key) {
return {
subCat: key,
tests: groupBySubCat[key]
};
});
var maingroups = Object.keys(groupBySubCat).map(function(key) {
return {
subCat: key,
tests: groupBySubCat[key]
};
});
Any improvement would be appreciated.
Upvotes: 1
Views: 62
Reputation: 6540
This function should do the job.
function getGroupedByCategory(list){
var ret = {}
for(var i=0;i<list.length;i++){
var mainCat = list[i].mainCat
var subCat = list[i].subCat
if(!ret[mainCat]) // check if mainCat key exists
ret[mainCat] = {} // if not create new object
if(!ret[mainCat][subCat]) // check if subCat exists in mainCat object
ret[mainCat][subCat] = [] // if not create new list
ret[mainCat][subCat].push(list[i]) // push current element in the designated list
}
return ret
}
Upvotes: 2