简体   繁体   中英

Sort a JavaScript object by key

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.

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM