1

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.

4
  • 1
    Is that a typo in the original json data? There are no brackets even though I would expect there to be an array. Commented Aug 27, 2017 at 22:21
  • Do you want to group them, or do you want to sort them? Notice that object properties are unordered. Commented Aug 27, 2017 at 22:37
  • your title mentions sort ... your code doesn't sort ... Commented Aug 27, 2017 at 23:08
  • Thanks, @Obsidian-Age for editing my code and clarify the bad vocabulary used.The point was to actually group and not sort. the answer offered by Manuel-Otto do exactly what I need. Commented Aug 28, 2017 at 7:50

1 Answer 1

2

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
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.